How can I get a random number in Kotlin?

后端 未结 22 1585
一个人的身影
一个人的身影 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:50

    Another way of implementing s1m0nw1's answer would be to access it through a variable. Not that its any more efficient but it saves you from having to type ().

    val ClosedRange.random: Int
        get() = Random().nextInt((endInclusive + 1) - start) +  start 
    

    And now it can be accessed as such

    (1..10).random
    

提交回复
热议问题