Generating random values in Kotlin

Kotlin provides a wide range of options to generate random values. As of Kotlin 1.3, Kotlin comes with its own multi-platform Random generator. To enable this, use the kotlin.random.Random class, which provides various methods to generate randomness.

Generate random booleans

To generate random booleans in Kotlin, you can use the nextBoolean method:

import kotlin.random.Random

println(Random.nextBoolean())    // true or false

Generate random numbers

To generate random numbers such as Floats, Integers and Doubles in Kotlin, you can use the following methods:

// Generate a random number between 0 and 1, eg 0.11226113619705458
// Generate a random float between 0 and 1, eg 0.5246514
// Generate a random long between `Long.MIN_VALUE` and `Long.MAX_VALUE` (inclusive), eg 4162351879473297809
// Generate a random int between `Int.MIN_VALUE` and `Int.MAX_VALUE` (inclusive), eg 1543627985

Generate random numbers within a certain range

If you want to have a bit more control over the range of random numbers generated, you can specify various options to the next... methods:

println(Random.nextDouble())           // value between 0 and 1, eg 0.5838455091335562
println(Random.nextDouble(5.0))        // value between 0 and 5, eg 4.953802809821396
println(Random.nextDouble(-5.0, 5.0))  // value between -5 and 5, eg -3.7408889198843234

Generate random bits and bytes

If you want to generate random bits or bytes, Kotlin provides the following methods:

println(Random.nextBits(3))                 // 3 bits: 010 => 2
println(Arrays.toString(Random.nextBytes(8)))   // [-63, 76, 116, ..., -1]

Generate random values using a seed

Two constructor-like functions (using either an Int or a Long) are provided to obtain a repeatable sequence generator, seeded with the specified number:

val random = Random(seed)

Generate random values using ranges

You can also generate a random value in Kotlin using ranges:

// Generate a random value between 0 and 10, inclusive

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

// Alternative

Leave a Reply

Your email address will not be published. Required fields are marked *