How can I get a random number in Kotlin?

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

    Using a top-level function, you can achieve exactly the same call syntax as in Ruby (as you wish):

    fun rand(s: Int, e: Int) = Random.nextInt(s, e + 1)
    

    Usage:

    rand(1, 3) // returns either 1, 2 or 3
    

提交回复
热议问题