How can I get a random number in Kotlin?

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

    If the numbers you want to choose from are not consecutive, you can use random().

    Usage:

    val list = listOf(3, 1, 4, 5)
    val number = list.random()
    

    Returns one of the numbers which are in the list.

提交回复
热议问题