In this article, we will see how to generate a random number in the given range using Kotlin.

Using random class from Kotlin standard library

By using the kotlin.random.Random class from the Kotlin standard library, we can generate a random number. To generate the random number within the given range we can use the nextInt() or nextDouble() functions along with start and end values.

See the following example for more information:

import kotlin.random.Random

fun main() {
    val random = Random.nextInt(1, 100)
    println("Random number between 1 and 100: $random")

In the above example, using Random.nextInt() we generate a random integer within the range of 1 to 100.

The first parameter indicates the start value which is inclusive whereas the second parameter indicates the end value which is exclusive. The generated random number is then printed to the console.

Using Random class from the java.util:

As an alternative way, we can also utilize the java.util.Random class, which is available in the Java standard library. The same can be used in Kotlin as well.

Following is the example:

import java.util.Random

fun main() {
    val random = Random().nextInt(100) + 1
    println("Random number between 1 and 100: $random")

Categorized in:

Tagged in: