Kotlin example

How to generate a random number in a range in Kotlin

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Call (1..6).random(): it returns an Int from 1 to 6, both ends included, and needs no import. With import kotlin.random.Random, Random.nextInt(1, 7) gives the same numbers, because its second argument, until, is exclusive. Random.nextDouble() gives a Double from 0.0 up to 1.0, list.random() picks an item and list.shuffled() returns the items in random order. For tokens and passwords, use java.security.SecureRandom.

Kotlin has its own random number API in kotlin.random, so you don't need java.util.Random or Math.random(). Ranges, lists, arrays and strings all have a random() extension, and the Random object has nextInt, nextDouble, nextLong and nextBoolean. The sections below cover whole numbers in a range and the exclusive until, the other number types, repeatable results with a seed, random items and shuffles, a random alphanumeric string, and the Java classes you will still meet, including SecureRandom for anything secret, then a table to pick from. Most outputs print checks rather than the numbers themselves, so they stay the same from run to run. Each example runs on this page: hit Run, then edit the code and run it again.

1(1..6).random() and Random.nextInt()Recommended

(min..max).random() is the most readable way to get a whole number in a range, and both ends are included. The Random object does the same with nextInt(from, until), where from is included and until is not: Random.nextInt(1, 7) is a dice roll, and nextInt(10) is 0 to 9. The exclusive end matches Java's nextInt(bound) and suits indexes, but it is the classic off-by-one when you want the top value too. Ranges written with until or ..< exclude the end in the same way. Random is not imported by default, so Random.nextInt needs import kotlin.random.Random; without it the compiler stops with Unresolved reference 'Random'.

RandomInRange.kt
import kotlin.random.Random

fun main() {
    // A dice roll: both ends of 1..6 are included
    val roll = (1..6).random()
    println("roll in 1..6: ${roll in 1..6}")

    // nextInt(from, until): until is exclusive, so this is 1 to 6 too
    val n = Random.nextInt(1, 7)
    println("n in 1..6: ${n in 1..6}")

    // nextInt(until) starts at 0: 0 to 9
    val digit = Random.nextInt(10)
    println("digit in 0..9: ${digit in 0..9}")

    // 10,000 draws each: which values ever came up?
    println(List(10_000) { (1..6).random() }.toSortedSet())
    println(List(10_000) { Random.nextInt(1, 7) }.toSortedSet())
    println(List(10_000) { Random.nextInt(1, 6) }.toSortedSet())
    println(List(10_000) { (0..<3).random() }.toSortedSet())

    // An empty range has nothing to pick
    try {
        (5..1).random()
    } catch (e: NoSuchElementException) {
        println(e.message)
    }
}

Output

The first three lines are checks, so they print true on every run whatever the numbers were. The sets show which values came up in 10,000 draws: (1..6).random() and Random.nextInt(1, 7) both give [1, 2, 3, 4, 5, 6], while Random.nextInt(1, 6) never reaches 6 and gives [1, 2, 3, 4, 5]. (0..<3).random() gives [0, 1, 2]. A range written backwards is empty, not reversed: (5..1).random() throws NoSuchElementException with Cannot get random in empty range: 5..1, so put the smaller number first.

2Random Doubles, Longs and Booleans

The other types follow the same pattern. Random.nextDouble() returns a value from 0.0 up to, but not including, 1.0, and nextDouble(from, until) moves that to any span. nextLong, nextFloat and nextBoolean work the same way, and a Long or Char range has random() as well. A Double range does not: (1.0..2.0).random() fails to compile with Unresolved reference 'random' on receiver of type 'ClosedFloatingPointRange<Double>'., so use nextDouble(1.0, 2.0). For a chance, compare a random Double with the probability.

RandomDouble.kt
import java.util.Locale
import kotlin.random.Random

fun main() {
    // nextDouble(): 0.0 up to, not including, 1.0
    val x = Random.nextDouble()
    println("x in [0, 1): ${x >= 0.0 && x < 1.0}")

    // nextDouble(from, until): a price from 5.00 to under 20.00
    val price = Random.nextDouble(5.0, 20.0)
    println("price in [5, 20): ${price >= 5.0 && price < 20.0}")
    val shown = String.format(Locale.US, "%.2f", price)
    println("two decimals: ${shown.substringAfter('.').length == 2}")

    // Long, Float, Char and Boolean
    val id = Random.nextLong(1_000_000_000_000, 10_000_000_000_000)
    println("id has 13 digits: ${id.toString().length == 13}")
    val f = Random.nextFloat()
    println("f in [0, 1): ${f >= 0f && f < 1f}")
    println("letter: ${('a'..'z').random() in 'a'..'z'}")
    val heads = List(1_000) { Random.nextBoolean() }.count { it }
    println("heads in 1,000 flips, 400 to 600: ${heads in 400..600}")

    // A 30% chance: compare nextDouble() with 0.3
    val hits = List(10_000) { Random.nextDouble() < 0.3 }.count { it }
    println("hits in 10,000, 2,700 to 3,300: ${hits in 2_700..3_300}")

    // Seeded so the exact values below repeat (see the next section)
    val rng = Random(42)
    println(rng.nextDouble(1.5, 2.5))
    println(rng.nextFloat())
    println(rng.nextLong(1_000_000_000_000))
}

Output

Every check prints true. The price check shows that nextDouble(5.0, 20.0) stays at or above 5.0 and below 20.0, and String.format with Locale.US rounds it to two decimals for display; without a locale, the decimal separator follows the machine. 1,000 coin flips land between 400 and 600 heads, and the 30% test hits between 2,700 and 3,300 times out of 10,000. The last three lines come from Random(42), so they repeat exactly: 1.7263152659723178, 0.90495676 and 230457923733.

3Repeatable numbers with a seeded Random(42)

Random(seed) creates a generator whose sequence depends only on the seed, so two generators with the same seed give the same numbers in the same order, on every run. That is what you want in tests, simulations you need to replay, and level generators in games. Pass the generator wherever a random value is made: random(rng), shuffled(rng) and rng.nextInt(…) all take it. A function that accepts a Random parameter, with the default Random, is random in production and predictable in a test. Note that Random() without a seed is not how you get an unseeded generator: the class is abstract, and the call fails with Cannot create an instance of an abstract class. Use the Random object itself.

SeededRandom.kt
import kotlin.random.Random

// Random by default, repeatable when a test passes Random(seed)
fun rollDice(count: Int, random: Random = Random): List<Int> =
    List(count) { random.nextInt(1, 7) }

fun main() {
    // Same seed, same sequence, on every run
    val a = Random(42)
    val b = Random(42)
    println(List(8) { a.nextInt(1, 7) })
    println(List(8) { b.nextInt(1, 7) })

    // Pass the generator to random() and shuffled() too
    val rng = Random(42)
    println(List(5) { (1..6).random(rng) })
    println(listOf("a", "b", "c", "d", "e").shuffled(Random(42)))

    // A different seed gives a different sequence
    println(rollDice(5, Random(7)))
    println(rollDice(5, Random(7)))
    println(rollDice(5).all { it in 1..6 })

    // The trap: a new Random(42) for every value repeats one value
    println(List(5) { Random(42).nextInt(100) })

    // java.util.Random(42) is a different algorithm
    println(Random(42).nextInt(100))
    println(java.util.Random(42).nextInt(100))
}

Output

The two generators seeded with 42 print the same [6, 1, 6, 3, 2, 1, 2, 3], and (1..6).random(rng) with a fresh Random(42) starts the same way, [6, 1, 6, 3, 2]. rollDice(5, Random(7)) gives [3, 6, 4, 3, 6] twice, while rollDice(5) uses the default and can only be checked, not predicted. The trap line prints [33, 33, 33, 33, 33]: every new Random(42) starts the sequence over, so create the generator once and reuse it. Kotlin's Random(42) and java.util.Random(42) use different algorithms, so their first nextInt(100) differs: 33 and 30.

4A random element, and shuffling a list

list.random() picks one item; it throws on an empty list, so use randomOrNull() when the list may be empty. shuffled() returns a new list in random order and leaves the original alone, while shuffle() reorders a MutableList in place. To draw several different items, shuffle and take(n): calling random() in a loop can pick the same item twice. Arrays, sets, strings and enum entries have random() too; for a map, pick from entries or keys. The example seeds the generator so its output stays the same.

RandomElement.kt
import kotlin.random.Random

enum class Suit { HEARTS, DIAMONDS, CLUBS, SPADES }

fun main() {
    val colors = listOf("red", "green", "blue", "yellow")
    println("picked a color: ${colors.random() in colors}")

    val rng = Random(42)
    println(colors.random(rng))

    // shuffled() returns a new list; the original is unchanged
    println(colors.shuffled(rng))
    println(colors)

    // Six different numbers from 1 to 49: shuffle, then take
    println((1..49).shuffled(rng).take(6).sorted())

    // Maps, enums, strings and arrays
    val prices = mapOf("tea" to 3, "coffee" to 4, "juice" to 5)
    val (item, price) = prices.entries.random(rng)
    println("$item costs $price")
    println(Suit.entries.random(rng))
    println("kotlin".random(rng))
    println(arrayOf("x", "y", "z").random(rng))

    // shuffle() reorders a MutableList in place
    val deck = (1..10).toMutableList()
    deck.shuffle(rng)
    println(deck)

    // An empty list: randomOrNull() or an exception
    val empty = emptyList<String>()
    println(empty.randomOrNull() ?: "nothing to pick")
    try {
        empty.random()
    } catch (e: NoSuchElementException) {
        println(e.message)
    }
}

Output

With the seed, colors.random(rng) picks red and shuffled(rng) gives [red, yellow, blue, green], while colors still prints in its original order. The lottery draw [2, 4, 11, 32, 36, 39] has six different numbers, because a shuffle never repeats an item. The map entry destructures into juice costs 5, and the enum, the string and the array give CLUBS, k and y. deck.shuffle(rng) changes deck itself. On the empty list, randomOrNull() returns null and the ?: fallback prints nothing to pick, while random() throws NoSuchElementException with Collection is empty.

5A random alphanumeric string

There is no built-in random string function. Build the alphabet once by adding character ranges, ('a'..'z') + ('A'..'Z') + ('0'..'9'), which gives a List<Char> of 62 characters, then pick one character per position and join them. CharArray(n) { … } or buildString does the same without the temporary list. This is fine for test data, file names and short display codes. For anything an attacker should not guess, such as session tokens, reset links or passwords, pass a SecureRandom instead (next section). For a unique ID rather than a random one, java.util.UUID.randomUUID() gives a 36-character string.

RandomString.kt
import kotlin.random.Random

// Letters and digits: 62 characters
val alphanumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')

fun randomString(length: Int, random: Random = Random): String =
    (1..length).map { alphanumeric.random(random) }.joinToString("")

fun main() {
    println(alphanumeric.size)

    val id = randomString(12)
    println("length: ${id.length}")
    println("alphanumeric: ${id.all { it in alphanumeric }}")

    // Seeded, so the same string comes back every run
    println(randomString(12, Random(42)))

    // Without the temporary list: fill a CharArray
    val rng = Random(42)
    println(String(CharArray(12) { alphanumeric.random(rng) }))

    // Any alphabet works: here, 8 hex digits
    val hex = buildString { repeat(8) { append("0123456789abcdef".random(rng)) } }
    println(hex)

    // A unique ID instead of a random string
    println(java.util.UUID.randomUUID().toString().length)
}

Output

The alphabet has 62 characters, and the unseeded string passes both checks: 12 characters, all of them letters or digits. With Random(42), the map version and the CharArray version build the same fCVSXQ767BUp, because they draw from the same sequence in the same order. The hex string 4b2f9113 continues from that generator. A UUID string is always 36 characters: 32 hex digits and four dashes.

6Java habits, and SecureRandom for tokens

Older answers and code converted from Java use java.util.Random, ThreadLocalRandom or Math.random(), often with the formula min + (int)(Math.random() * (max - min + 1)). All of them still work, but write java.util.Random in full so it can't be mixed up with kotlin.random.Random. The Kotlin calls replace them line for line, and on the JVM the Random object already hands the work to ThreadLocalRandom, so it is safe to share between threads. None of these generators is meant for secrets: their output can be predicted. For tokens, keys and passwords use java.security.SecureRandom, and asKotlinRandom() lets it drive random() and shuffled().

SecureToken.kt
import java.security.SecureRandom
import java.util.Base64
import java.util.concurrent.ThreadLocalRandom
import kotlin.random.asKotlinRandom

fun main() {
    // Java habits: each one gives 1 to 6
    val a = java.util.Random().nextInt(6) + 1
    val b = ThreadLocalRandom.current().nextInt(1, 7)
    val c = (Math.random() * 6).toInt() + 1
    println("all in 1..6: ${listOf(a, b, c).all { it in 1..6 }}")

    // A session token: 32 secure random bytes, URL-safe Base64
    val secure = SecureRandom()
    val bytes = ByteArray(32)
    secure.nextBytes(bytes)
    val token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
    val urlSafe = ('a'..'z') + ('A'..'Z') + ('0'..'9') + '-' + '_'
    println("token length: ${token.length}")
    println("URL-safe: ${token.all { it in urlSafe }}")

    // asKotlinRandom(): SecureRandom behind random() and shuffled()
    val alphanumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9')
    val rng = secure.asKotlinRandom()
    val password = (1..16).map { alphanumeric.random(rng) }.joinToString("")
    println("password length: ${password.length}")
    println("alphanumeric: ${password.all { it in alphanumeric }}")
}

Output

The three Java forms all land in 1 to 6. The token is 43 characters long: 32 bytes in Base64 without padding, using only letters, digits, - and _, so it can go in a URL as it is. The password comes from the same SecureRandom through asKotlinRandom(), which needs import kotlin.random.asKotlinRandom; without the import the call is an Unresolved reference. Prefer the token for anything a program reads, and keep the alphabet approach for codes a person has to type.

7Which should you use?

MethodGivesRangeBest for
(1..6).random()IntBoth ends includedWhole numbers; no import
Random.nextInt(1, 7)Intuntil is excludedIndexes, code ported from Java
Random.nextDouble(a, b)Doubleb is excludedDecimals, probabilities
Random(42)A seeded generatorSame sequence every runTests, replays, games
list.random(), shuffled()An item, a new listrandom() throws when emptyPicks, draws without repeats
SecureRandomBytes, or a Random via asKotlinRandom()UnpredictableTokens, passwords, keys
java.util.Random, Math.random()Int, DoubleBound excludedAvoid: kotlin.random does the same

Frequently asked questions

Is the until in Random.nextInt(from, until) inclusive?

No. until is exclusive, so Random.nextInt(1, 6) gives 1 to 5 and never 6; write Random.nextInt(1, 7) for a dice roll, or use (1..6).random(), where both ends are included. nextInt(10) gives 0 to 9. When the two arguments are equal there is nothing to pick, and both throw IllegalArgumentException: a seeded generator says Random range is empty: [5, 5)., the Random object says bound must be greater than origin.

How do I get random numbers without repeats?

Shuffle the range and take what you need: (1..49).shuffled().take(6) gives six different numbers. Calling random() six times can return the same number twice. For a large range and a few picks, add random() results to a mutableSetOf<Int>() until it has the size you want.

Why does Random(42) give the same numbers every time?

Because a seed fixes the whole sequence: that is the point of seeding. Use the Random object (Random.nextInt(...) or plain (1..6).random()) when you want different numbers on each run. Also create the seeded generator once: Random(42).nextInt(100) inside a loop starts a fresh sequence each time and prints 33 over and over.

Will Random(42) give the same sequence in every Kotlin version?

The Kotlin documentation only promises the same sequence for the same seed within one version of the Kotlin runtime; a later version may change the algorithm. For test data that must never change, store the expected values or the generated data, not only the seed. java.util.Random(42) is a different algorithm: its first nextInt(100) is 30, where Kotlin's is 33.

Is kotlin.random.Random thread-safe?

The Random object is: on the JVM it delegates to ThreadLocalRandom, so you can call Random.nextInt from any thread without a lock. A seeded Random(42) keeps its own state, so share one between threads and the sequence is no longer repeatable; give each thread its own generator.

How do I pick a random enum value?

Call random() on the entries: Suit.entries.random(). On projects older than Kotlin 1.9, where entries is not available, use Suit.values().random().

Run it yourself

Open any of these in the full Kotlin editor to tweak, run and share.

Kotlin playground