By Alvin Alexander. Last updated: August 11, 2022
If you need to generate a small random number in Kotlin, I find that this approach works:
val r = (1..10).shuffled().first()
That code generates a single random number in the range from 1 to 10 (including 1 on the low end and 10 on the high end).
You can use the technique to simulate the rolling of a dice (die):
val r = (1..6).shuffled().first()
Or simulate flipping a coin (0=heads, 1=tails, or vice versa):
val r = (1..2).shuffled().first()
This also works for the coin flip simulation:
val r = listOf(1,2).shuffled().first()