How can I get a random number in Kotlin?

Generate a random integer between from(inclusive) and to(exclusive)

import java.util.Random

val random = Random()

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

My suggestion would be an extension function on IntRange to create randoms like this: (0..10).random()

TL;DR Kotlin >= 1.3, one Random for all platforms

As of 1.3, Kotlin comes with its own multi-platform Random generator. It is described in this KEEP. The extension described below is now part of the Kotlin standard library, simply use it like this:

val rnds = (0..10).random() // generated random from 0 to 10 included

Kotlin < 1.3

Before 1.3, on the JVM we use Random or even ThreadLocalRandom if we're on JDK > 1.6.

fun IntRange.random() = 
       Random().nextInt((endInclusive + 1) - start) + start

Used like this:

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

If you wanted the function only to return 1, 2, ..., 9 (10 not included), use a range constructed with until:

(0 until 10).random()

If you're working with JDK > 1.6, use ThreadLocalRandom.current() instead of Random().

KotlinJs and other variations

For kotlinjs and other use cases which don't allow the usage of java.util.Random, see this alternative.

Also, see this answer for variations of my suggestion. It also includes an extension function for random Chars.

Tags:

Random

Jvm

Kotlin