A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n)
.
Any suggestion?
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