Kotlin – Random Value from a Range

Get Random Value from a Range in Kotlin

To get a random value from a given range in Kotlin, call random() function on the range object. The function returns a random element from this range.

For example, if would like to pick a random number from a range [4, 25], use the following syntax.

val randomNumber = (4..25).random()

Examples

In the following examples, you will learn how to get a random element from given range.

1. Get random number from a range of numbers

In the following program, we take an integer range 4..25, pick a random number from this range, and print it to output.

Kotlin Program

fun main() {
    val myRange = 4..25
    val randomNumber = myRange.random()
    print(randomNumber)
}

Output 1

8

Output 2

15

2. Get random character from a character range

In the following program, we take an character range 'a'..'s', pick a random character from this range, and print it to output.

Kotlin Program

fun main() {
    val myRange = 'a'..'s'
    val randomChar = myRange.random()
    print(randomChar)
}

Output 1

r

Output 2

j