How can I get a random number in Kotlin?


Kotlin provides multiple ways to generate a random number. In this article, we will see different ways to generate a random number and access it throughout the program.

Example – Using Random class

Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random.

As per the Kotlin documentation, the companion object Random.Default is the default instance of Random class. In the following example, we will generate a list of random values with int (1-30) .

Example

import kotlin.random.Random

fun main() {
   val myRandomValues = List(5) { Random.nextInt(0, 30) }

   // Prints a new sequence every time
   println(myRandomValues)

}

Output

It generated the following random numbers. You may get a different set of numbers, as the output is random in nature.

[8, 21, 16, 29, 16]

Example – Using random()

Kotlin does provide a random() function to generate random numbers. It takes a series of numbers as an input and it returns a random Int as an output.

Example

fun main() {
   // It generates a random number between 0 to 10
   println((0..10).random())
}

Output

On execution, it produced the following output −

0

Example – Using shuffled()

Kotlin does provide another method to generate random numbers between a sequence. We can use shuffled() to generate a random number in between 1 to 100.

Example

fun main() {
   val random1 = (0..100).shuffled().last()
   println(random1)
}

Output

On execution, it produced the following output. It could be different in your case, as the output is random in nature.

42

Updated on: 27-Oct-2021

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements