A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n)
.
Any suggestion?
My suggestion would be an extension function on IntRange to create randoms like this: (0..10).random()
As of 1.3, Kotlin comes with its own multi-platform Random generator. It is described in this KEEP. The extension described below is now part of the Kotlin standard library, simply use it like this:
val rnds = (0..10).random() // generated random from 0 to 10 included
Before 1.3, on the JVM we use Random
or even ThreadLocalRandom
if we're on JDK > 1.6.
fun IntRange.random() =
Random().nextInt((endInclusive + 1) - start) + start
Used like this:
// will return an `Int` between 0 and 10 (incl.)
(0..10).random()
If you wanted the function only to return 1, 2, ..., 9
(10
not included), use a range constructed with until
:
(0 until 10).random()
If you're working with JDK > 1.6, use ThreadLocalRandom.current()
instead of Random()
.
KotlinJs and other variations
For kotlinjs and other use cases which don't allow the usage of java.util.Random
, see this alternative.
Also, see this answer for variations of my suggestion. It also includes an extension function for random Char
s.