https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Sourabh Rawat

10/22/2020, 6:13 PM
What would be the kotlin way to write below code:
Copy code
var toPlayer = players.random()
                while (toPlayer == fromPlayer) {
                    toPlayer = players.random()
}
I am not liking the multiple assignments + var here...
s

Sebastian Galkin

10/22/2020, 6:19 PM
How about something like
Copy code
val toPlayers = generateSequence {players.random()}.filter {it != fromPlayer}
that gives you an infinite stream of players that are not
fromPlayer
s

Sourabh Rawat

10/22/2020, 6:32 PM
interesting. just what I needed. Thank you!
n

nanodeath

10/22/2020, 6:41 PM
make sure there are at least two players 😅
I guess that's a requirement regardless
r

Ruckus

10/22/2020, 6:43 PM
(players - fromPlayer).random()
1
s

Sebastian Galkin

10/22/2020, 6:43 PM
nice!
n

nanodeath

10/22/2020, 6:44 PM
it does duplicate the array, but also who cares 🙂
🤔 1
😂 1
r

Ruckus

10/22/2020, 6:51 PM
You could also define a helper function like so:
Copy code
fun <T> List<T>.randomBut(exclude: T): T {
    var value: T
    do value = random() while (value == exclude)
    return value
}
Then just do
Copy code
players.randomBut(fromPlayer)
Or more general:
Copy code
inline fun <T> List<T>.randomWhere(predicate: (T) -> Boolean): T {
    var value: T
    do value = random() while (!predicate(value))
    return value
}
And
Copy code
players.randomWhere { it != fromPlayer }
s

Sourabh Rawat

10/22/2020, 7:07 PM
yes. thats doable. But I didnt want to write the do while + var combo, even in a helper, myself.
r

Ruckus

10/22/2020, 7:09 PM
Fair enough, and not worth it for a single use, but with keeping in mind if you find yourself doing it a lot.
n

nanodeath

10/22/2020, 7:11 PM
I've never seen a one-liner do-while loop before...huh
👍 1
s

Sourabh Rawat

10/22/2020, 7:13 PM
Me too. I thought this do while + assignment was only possible in Java.
🏳️‍🌈 1
b

bjonnh

10/22/2020, 7:39 PM
See
Copy code
doWhileStatement
(used by loopStatement)
  : 'do' controlStructureBody? 'while' '(' expression ')'
  ;
in https://kotlinlang.org/docs/reference/grammar.html#whileStatement
🤯 1
you can even write: "do while (value == exclude)"
and it is valid grammar…
m

Michael de Kaste

10/23/2020, 10:05 AM
anything with random that can't mutually exclude itself from the edge case where it needs to check again is bad in my opinion. in that case I feel that the following code from Ruckus is the best
Copy code
(players - fromPlayer).random()
Yes you could technically use some sort of smart indexer where you exclude the result, but that would include searching for that element in the first place so the complexity would be the same.
3 Views