randomkotlinjvm

How can I get a random number in Kotlin?


A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n).

Any suggestion?


Solution

  • My suggestion would be an extension function on IntRange to create randoms like this: (0..10).random()

    TL;DR Kotlin >= 1.3, one Random for all platforms

    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() // generates random from 0 to 10 (inclusive)
    

    Kotlin < 1.3

    Before 1.3, on the JVM, we used Random, or even ThreadLocalRandom for JDK > 1.6.

    fun IntRange.random() = 
           Random().nextInt((endInclusive + 1) - start) + start
    

    To then do:

    // will return an `Int` between 0 and 10 (incl.)
    (0..10).random()
    

    If you wanted the function to return 1-9 (10 not included), prefer 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 Chars.