How can I get a random number in Kotlin?

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

    Generate a random integer between from(inclusive) and to(exclusive)

    import java.util.Random
    
    val random = Random()
    
    fun rand(from: Int, to: Int) : Int {
        return random.nextInt(to - from) + from
    }
    

提交回复
热议问题