Skip to content

Random

class Random

Random control helper. See random.

Functions

accessUnsafe

suspend fun accessUnsafe(): Random

Gives uncontrolled access to the underlying Random.

Warning. The Kotlin standard library's random generator is not thread-safe. This class wraps it with the necessary synchronization mechanisms. By using accessUnsafe, you are bypassing them. Incorrect usage of this function may break the random generation and reproducibility guarantees of this class.

In most cases, use is probably sufficient.

nextBits

suspend fun Random.nextBits(bitCount: Int): Int

Generates random bits.

See also

nextBoolean

suspend fun Random.nextBoolean(): Boolean

Generates a random boolean.

See also

nextDouble

suspend fun Random.nextDouble(): Double

Generates a random double.

See also

suspend fun Random.nextDouble(from: Double, until: Double): Double

Generates a random double.

See also

nextFloat

suspend fun Random.nextFloat(): Float

Generates a random float.

See also

nextInt

suspend fun Random.nextInt(): Int

Generates a random integer.

See also

suspend fun Random.nextInt(from: Int, until: Int): Int

Generates a random integer.

See also

nextLong

suspend fun Random.nextLong(): Long

Generates a random integer.

See also

suspend fun Random.nextLong(from: Long, until: Long): Long

Generates a random integer.

See also

setSeed

suspend fun setSeed(seed: Long)

Initializes the underlying Random implementation with seed.

Example:

val int by randomInt()

test("This is a test") {
    setSeed(123456789L)

    // Even if prepared values are declared outside the test,
    // as long as they are accessed after the seed is set,
    // they respect the configured seed.
    println("Generated number: ${int()}")
}

This function is meant to easily allow reproducing a test failure that only arrives in rare cases by simply adding it at the start of the test with the seed of the failed execution.

This function can only be called before the first random value is generated for the current test, otherwise it throws IllegalStateException.

use

suspend fun <T> use(block: (Random) -> T): T

Provides block with the underlying Random source.

Warning. The Kotlin standard library's random generator is not thread-safe. This class ensures only a single thread may call this function at once. It is therefore unsafe to access the provided generator after the call to this function has ended.