How to get a random number in Kotlin?

5

How can I get a random number between two values? As ruby does with rand(0..n)

    
asked by anonymous 26.01.2018 / 19:48

1 answer

5

There are a few ways to solve this problem:

A normal method:

The first and most intuitive is to create a function that returns a random number using the class java.util.Random :

import java.util.Random

val random = Random()

fun rand(from: Int, to: Int) : Int {
    return random.nextInt(to - from) + from // from(incluso) e to(excluso)
}

Extensive functions:

Another more interesting way is to use extensive functions:

fun ClosedRange<Int>.random() = 
     Random().nextInt(endInclusive - start) +  start

Soon after you can use it as follows:

(0..10).random() // => retorná um númeor entre 0 e 9 (incluso)
  

Source: link

    
26.01.2018 / 19:48