How to get a random number in Kotlin?

Asked

Viewed 1,167 times

5

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

1 answer

6


There are some 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 as follows:

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

Source: https://stackoverflow.com/questions/45685026/how-can-i-get-a-random-number-in-kotlin

  • I found this method by extensive functions very intriguing. Very good to know more and more of Kotlin just in reading answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.