choiceOrNull

fun <T> Random.choiceOrNull(array: Array<T>): T?

Returns a random element from this array using the specified source of randomness, or null if this array is empty.

Example:

Random.choiceOrNull(arrayOf(1..5)) // a number in the range 1..5
Random.choiceOrNull(arrayOf()) // null

Since

1.1.0

See also

randomOrNull

fun <T> Random.choiceOrNull(collection: Collection<T>): T?

Returns a random element from this collection using the specified source of randomness, or null if this collection is empty.

Example:

Random.choiceOrNull(listOf(1..5)) // a number in the range 1..5
Random.choiceOrNull(listOf()) // null

Since

1.1.0

See also

randomOrNull

inline fun <T, K> Random.choiceOrNull(map: Map<T, K>): Pair<T, K>?

Returns a random element from this map using the specified source of randomness, or null if this map is empty.

Example:

Random.choice(mapOf(1 to 1, 2 to 2, 3 to 3, 4 to 4, 5 to 5)) // a pair from this map
Random.choice(mapOf()) // null

Since

1.1.0