0

I have a variable which gets a value from a function. The function generates a random string from a list. However when I call the variable it has the value from the first time it was called. How do I get the variable to call the function every time so it has a new value each time it is called?

My code is:

player1gen(List players) {
  //players[Random().nextInt(players.length)];
  return players[Random().nextInt(players.length)].toString();
}

String player1 = player1gen(players);

3
  • Can you share mode details like where you declared that function and from where you are calling that one ? Commented Aug 10, 2022 at 7:54
  • Is it the same question as your last one? Commented Aug 10, 2022 at 7:56
  • @YeasinSheikh it is related to my last question which has now been resolved, thanks. Commented Aug 10, 2022 at 8:14

1 Answer 1

1

You can do

String get player1 => player1gen(players);
Sign up to request clarification or add additional context in comments.

2 Comments

@Entrebear While this does what you want, I would advise against it. It is unusual for a getter (which to callers looks like a normal variable access) to return different values. It would be much more readable for player1 to be a function.
@jamesdlin yeah, I agree

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.