Kotlin Generate Random Number with examples

This tutorial provides insights into generating random numbers and alphanumeric strings in Kotlin. A random number is a unique value generated for each execution.

Generating Random Numbers in Kotlin

There are multiple approaches to generating random numbers in Kotlin:

  • Using kotlin.random.Random class:

The Random class includes a nextInt function that produces a random number within a specified range.



min and max is a number or range of numbers.

Here’s an example that prints a random number less than 10 for each execution:

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

Note: This requires Kotlin SDK version 1.3 or higher.

To generate random numbers within a specific range (between two numbers), the following example generates 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)


Generating Random Strings in Kotlin

In certain scenarios, there’s a need to generate random strings in Kotlin.

The following example demonstrates generating a unique random string with alphanumeric characters:

  • Define the allowed characters within the function.
  • Iterate through characters using map, shuffle, and return the sub-string of the given length.
fun main() {

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

This function generates a random string of the specified length using a shuffled subset of alphanumeric characters.