How can I get a random number in Kotlin?

后端 未结 22 1609
一个人的身影
一个人的身影 2020-12-12 15:02

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

Any suggestion?

22条回答
  •  天涯浪人
    2020-12-12 15:52

    Possible Variation to my other answer for random chars

    In order to get random Chars, you can define an extension function like this

    fun ClosedRange.random(): Char = 
           (Random().nextInt(endInclusive.toInt() + 1 - start.toInt()) + start.toInt()).toChar()
    
    // will return a `Char` between A and Z (incl.)
    ('A'..'Z').random()
    

    If you're working with JDK > 1.6, use ThreadLocalRandom.current() instead of Random().

    For kotlinjs and other use cases which don't allow the usage of java.util.Random, this answer will help.

    Kotlin >= 1.3 multiplatform support for Random

    As of 1.3, Kotlin comes with its own multiplatform Random generator. It is described in this KEEP. You can now directly use the extension as part of the Kotlin standard library without defining it:

    ('a'..'b').random()
    

提交回复
热议问题