How can I get a random number in Kotlin?

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

    You can create an extension function similar to java.util.Random.nextInt(int) but one that takes an IntRange instead of an Int for its bound:

    fun Random.nextInt(range: IntRange): Int {
        return range.start + nextInt(range.last - range.start)
    }
    

    You can now use this with any Random instance:

    val random = Random()
    println(random.nextInt(5..9)) // prints 5, 6, 7, or 8
    

    If you don't want to have to manage your own Random instance then you can define a convenience method using, for example, ThreadLocalRandom.current():

    fun rand(range: IntRange): Int {
        return ThreadLocalRandom.current().nextInt(range)
    }
    

    Now you can get a random integer as you would in Ruby without having to first declare a Random instance yourself:

    rand(5..9) // returns 5, 6, 7, or 8
    

提交回复
热议问题