Kotlin – Generate a Random Number in specific Range

Generate a Random Number in specific Range in Kotlin

To generate a random number in specific range in Kotlin, you can use random() function of the IntRange class.

Create a range object with the minimum value min and maximum value max of the specified range, and call random() function on the range object.

(min..max).random()

where

  • min is the minimum value of specified range.
  • max is the maximum value of specified range.

The function returns a value that is randomly picked in the given integer range.

Examples

Pick a random number between 40 and 80

In the following program, we take a range object with a minimum value of 40, and maximum value of 80. Then we get a random number from the range object using random() function, and print the returned number to output.

Kotlin Program

fun main() {
    val min = 40
    val max = 80
    val randomNumber = (min..max).random()
    println(randomNumber)
}

Output 1

68

Output 2

43

Run the program as many times you would like, and a random number from the specified range would be print out.

Generate a random number between 0 and 10

Now, let us write a program to generate a random number between 0 and 10.

Kotlin Program

fun main() {
    val min = 0
    val max = 10
    val randomNumber = (min..max).random()
    println(randomNumber)
}

Output 1

5

Output 2

2