Question
How can I generate a random integer in Kotlin using a reusable approach, similar to Ruby's rand(0..n)?
I want a generic way to return a random integer between two parameters, such as a minimum and maximum value.
Short Answer
By the end of this page, you will understand how random number generation works in Kotlin, how to generate integers within a range, how range boundaries behave, and how to wrap this logic in a reusable function for everyday coding tasks.
Concept
In Kotlin, random number generation is commonly done with the standard library's random utilities, especially kotlin.random.Random and range helpers like IntRange.random().
For beginners, the key idea is this: you usually do not generate any possible integer and then manually limit it. Instead, Kotlin lets you ask for a random number inside a specific range.
For example:
val n = (0..10).random()
This returns a random Int from 0 to 10, inclusive.
If you need two parameters, such as min and max, you can create a range from them:
fun randomBetween(min: Int, max: Int): Int {
return (min..max).random()
}
This matters in real programming because random values are used in many places:
- games
- simulations
- testing
- shuffling
- selecting sample data
- generating temporary values
A very important detail is whether the upper bound is included or excluded. Kotlin ranges like min..max are inclusive, which means both ends are possible results.
Kotlin also supports Random.nextInt(from, until), where the second argument is exclusive:
val n = Random.nextInt(0, 10)
This returns a number from 0 up to 9, not 10.
So there are two common styles in Kotlin:
(min..max).random()→ inclusive rangeRandom.nextInt(min, maxExclusive)→ exclusive upper bound
Choosing the right one prevents off-by-one bugs.
Mental Model
Think of a range like a numbered row of boxes.
If you write:
2..5
you are creating these boxes:
- 2
- 3
- 4
- 5
When you call .random(), Kotlin picks one box at random.
Now think of Random.nextInt(from, until) as a door rule:
fromcan enteruntilcannot enter
So:
Random.nextInt(2, 5)
can return:
- 2
- 3
- 4
but not 5.
This simple inclusive-vs-exclusive difference is the main thing to remember.
Syntax and Examples
Basic range syntax
val number = (0..10).random()
This returns a random integer between 0 and 10, including both values.
Reusable function
fun randomBetween(min: Int, max: Int): Int {
return (min..max).random()
}
fun main() {
println(randomBetween(1, 6))
}
This is useful when you want a function that works like rand(min..max).
Using Random.nextInt
import kotlin.random.Random
fun main() {
val number = Random.nextInt(1, 7)
println(number)
}
This returns a random number from to because is excluded.
Step by Step Execution
Consider this code:
fun randomBetween(min: Int, max: Int): Int {
require(min <= max) { "min must be less than or equal to max" }
return (min..max).random()
}
fun main() {
val value = randomBetween(3, 8)
println(value)
}
Step by step:
main()starts running.randomBetween(3, 8)is called.- Inside the function,
require(min <= max)checks whether3 <= 8. - The condition is true, so execution continues.
(min..max)creates the range3..8..random()picks one integer from this range.- Possible values are
3,4,5,6, , or .
Real World Use Cases
Random numbers appear in many common programming tasks.
Games
val diceRoll = (1..6).random()
Used for dice, enemy damage, loot drops, or random movement.
Picking a random item
val names = listOf("Ana", "Ben", "Cara")
val randomName = names.random()
Useful for selecting a winner, rotating tasks, or sampling data.
Temporary test data
val age = (18..65).random()
Helpful when generating fake users or mock records.
Simulations
You may need random values for weather, traffic, queue lengths, or experiments.
Security note
For passwords, tokens, or cryptographic secrets, ordinary random helpers are usually not the right tool. Use a secure randomness source when security matters.
Real Codebase Usage
In real Kotlin codebases, developers often wrap random logic in small helper functions so the rest of the app stays readable.
Validation before generating
fun randomBetween(min: Int, max: Int): Int {
require(min <= max) { "min must be less than or equal to max" }
return (min..max).random()
}
This is a common validation pattern.
Guard clauses
Developers often reject bad input early:
fun randomDiscount(min: Int, max: Int): Int {
require(min >= 0) { "min cannot be negative" }
require(max <= 100) { "max cannot be greater than 100" }
require(min <= max) { "min must be <= max" }
return (min..max).random()
}
Reproducible randomness for testing
In tests, developers may use a specific Random instance with a fixed seed so results are repeatable.
import kotlin.random.Random
rng = Random()
value = rng.nextInt(, )
Common Mistakes
1. Forgetting whether the upper bound is included
Broken expectation:
import kotlin.random.Random
val n = Random.nextInt(0, 10)
println(n) // many beginners expect 10 to be possible
10 will not be returned here.
Fix:
val n = (0..10).random()
or
val n = Random.nextInt(0, 11)
2. Not validating min and max
Broken code:
fun randomBetween(min: Int, max: Int): Int {
return (min..max).random()
}
If min > max, this may fail.
Comparisons
| Approach | Example | Upper bound | Best use |
|---|---|---|---|
Range with .random() | (1..6).random() | Inclusive | Clear, readable integer ranges |
Random.nextInt(from, until) | Random.nextInt(1, 7) | Exclusive | Precise control, common API style |
Collection .random() | list.random() | Not range-based | Picking a random element |
.random() on a range vs Random.nextInt()
- Use
(min..max).random()when you want code that clearly says “pick from this inclusive range.”
Cheat Sheet
Quick reference
Inclusive random integer
val n = (min..max).random()
Returns a value from min to max, inclusive.
Exclusive upper bound
import kotlin.random.Random
val n = Random.nextInt(min, maxExclusive)
Returns a value from min up to maxExclusive - 1.
Reusable helper
fun randomBetween(min: Int, max: Int): Int {
require(min <= max)
return (min..max).random()
}
Important rules
min..maxincludes both ends.Random.nextInt(from, until)excludesuntil.- Validate input when building helper functions.
- Random values can repeat.
- Use secure randomness for security-sensitive tasks.
FAQ
How do I generate a random number between two values in Kotlin?
Use an inclusive range:
val n = (min..max).random()
Is the maximum value included in Kotlin random ranges?
Yes, with (min..max).random(), both min and max are possible.
What is the difference between .random() and Random.nextInt() in Kotlin?
.random() on a range is inclusive. Random.nextInt(from, until) uses an exclusive upper bound.
How do I make a reusable random function in Kotlin?
Create a helper:
fun randomBetween(min: Int, max: Int): Int {
require(min <= max)
return (min..max).random()
}
Can Kotlin generate random items from a list?
Yes:
val item = myList.random()
Mini Project
Description
Build a simple Kotlin program that simulates rolling a custom dice. The user provides a minimum and maximum value, and the program prints a random result in that range. This demonstrates reusable random number generation, input validation, and range-based randomness.
Goal
Create a reusable Kotlin function that returns a random integer between two inclusive bounds and use it in a small console program.
Requirements
- Create a function that accepts
minandmaxas parameters. - Validate that
minis less than or equal tomax. - Return a random integer within the inclusive range.
- Call the function several times from
main()and print the results.
Keep learning
Related questions
Accessing Kotlin Extension Functions from Java
Learn how Kotlin extension functions are compiled and how to call them correctly from Java with clear examples and common pitfalls.
Android AlarmManager Example: Scheduling Tasks with AlarmManager
Learn how to use Android AlarmManager to schedule tasks, set alarms, and handle broadcasts with a simple beginner example.
Android Foreground Service Notification Channels in Kotlin
Learn why startForeground fails on Android 8.1 and how to create a valid notification channel for foreground services in Kotlin.