To get a random Int number in Kotlin use the following method:
import java.util.concurrent.ThreadLocalRandom
fun randomInt(rangeFirstNum:Int, rangeLastNum:Int) {
val randomInteger = ThreadLocalRandom.current().nextInt(rangeFirstNum,rangeLastNum)
println(randomInteger)
}
fun main() {
randomInt(1,10)
}
// Result – random Int numbers from 1 to 9
Building off of @s1m0nw1 excellent answer I made the following changes.
Code:
Test Case:
No need to use custom extension functions anymore. IntRange has a
random()
extension function out-of-the-box now.to be super duper ))
If the numbers you want to choose from are not consecutive, you can use
random()
.Usage:
Returns one of the numbers which are in the list.
Hope this helps.
Kotlin >= 1.3, multiplatform support for Random
As of 1.3, the standard library provided multi-platform support for randoms, see this answer.
Kotlin < 1.3 on JavaScript
If you are working with Kotlin JavaScript and don't have access to
java.util.Random
, the following will work:Used like this: