Kotlin Generate Random Number with examples

This tutorial explains How to generate Random Numbers and alpha n numeric strings in Kotlin. Random Number is a unique number that generates for every execution.

How to Generate Random Numbers in Kotlin

There are multiple ways to generate random numbers in Kotlin

  • using kotlin.random.Random class

    The Random class has a nextInt function that returns a Random number for a given limit

Syntax

Random.nextInt(min,max)

min and max is a number or range of numbers.

The below program prints the Random number less than 10 for every execution.

import kotlin.random.Random
fun main() {
    val randomNumber = Random.nextInt(10)
    println(randomNumber)
}

This only works if the Kotlin SDK version is greater than 1.3.

If you want generate random numbers between two numbers

Below example Get a Random number between 10 and 20

import kotlin.random.Random
fun main() {
    // Generates a number between inclusive of 10 and 20
    val randomNumber1 = Random.nextInt(10,20)
    println(randomNumber1)

}

How to Generate Random String in Kotlin

Sometimes, We need to generate Random String in Kotlin.

The below example generates a unique random string of alphanumeric

  • Define the allowed characters string in the function
  • Iterate characters using map, shuffle and return the sub-string of given length
fun main() {
    println(getRandomString(10))

}
fun getRandomString(length: Int): String {
    val characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmopqrstuvwxyz0123456789"
    return (characters).map { it }.shuffled().subList(0, length).joinToString("")
}