How can I get a random number in Kotlin?

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

    Kotlin >= 1.3, multiplatform support for Random

    As of 1.3, the standard library provided multi-platform support for randoms, see this answer.

    Kotlin < 1.3 on JavaScript

    If you are working with Kotlin JavaScript and don't have access to java.util.Random, the following will work:

    fun IntRange.random() = (Math.random() * ((endInclusive + 1) - start) + start).toInt()
    

    Used like this:

    // will return an `Int` between 0 and 10 (incl.)
    (0..10).random()
    

提交回复
热议问题