Random Numbers in Kotlin

Kotlin’s kotlin.random package provides pseudorandom number generation.

import kotlin.random.Random

fun main() {
    // For example, Random.nextInt returns a random Int n,
    // 0 <= n < 100.
    print("${Random.nextInt(100)},")
    print(Random.nextInt(100))
    println()

    // Random.nextDouble returns a Double f,
    // 0.0 <= f < 1.0.
    println(Random.nextDouble())

    // This can be used to generate random doubles in
    // other ranges, for example 5.0 <= f' < 10.0.
    print("${Random.nextDouble(5.0, 10.0)},")
    print(Random.nextDouble(5.0, 10.0))
    println()

    // If you want a known seed, create a new
    // Random instance with a specific seed.
    val r2 = Random(42)
    print("${r2.nextInt(100)},")
    print(r2.nextInt(100))
    println()

    // Creating another Random instance with the same seed
    // will produce the same sequence of numbers.
    val r3 = Random(42)
    print("${r3.nextInt(100)},")
    print(r3.nextInt(100))
    println()
}

To run the program, save it as RandomNumbers.kt and use the Kotlin compiler:

$ kotlinc RandomNumbers.kt -include-runtime -d RandomNumbers.jar
$ java -jar RandomNumbers.jar
68,56
0.8090228139659177
7.840125017402497,8.937056298890035
94,49
94,49

Some of the generated numbers may be different when you run the sample.

See the kotlin.random package docs for references on other random quantities that Kotlin can provide.