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 1 to 6 because 7 is excluded.
Inclusive version built from nextInt
import kotlin.random.Random
fun randomBetween(min: Int, max: Int): Int {
require(min <= max) { "min must be less than or equal to max" }
return Random.nextInt(min, max + 1)
}
This works, but you must be careful with max + 1 when max is very large.
Best beginner-friendly option
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 clear, readable, and matches the meaning of an inclusive range very well.
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,7, or8. - That chosen value is returned to
main(). println(value)prints it.
If the random choice happened to be 6, the output would be:
6
If you called randomBetween(8, 3), the require check would fail and throw an exception immediately. That is helpful because it catches invalid input early.
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
val rng = Random(1234)
val value = rng.nextInt(1, 10)
This is useful when you want predictable test behavior.
Random selection from collections
val servers = listOf("api-1", "api-2", "api-3")
val server = servers.random()
This can be used for simple balancing, sampling, or non-deterministic behavior in demos and tools.
Data generation scripts
Random values are often used in scripts that generate sample records for development databases or test fixtures.
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.
Fix:
fun randomBetween(min: Int, max: Int): Int {
require(min <= max) { "min must be less than or equal to max" }
return (min..max).random()
}
3. Using max + 1 carelessly
Potentially risky:
Random.nextInt(min, max + 1)
This can be a problem if max is already Int.MAX_VALUE.
Safer beginner option:
(min..max).random()
4. Assuming random means unique
Broken assumption:
println((1..3).random())
println((1..3).random())
These values can repeat. Random does not mean no duplicates.
If you need unique results, use a different approach such as shuffling.
5. Using normal random APIs for security-sensitive values
Do not use basic random generation for authentication codes, secret tokens, or password generation unless you are using a secure source designed for that purpose.
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.” - Use
Random.nextInt(min, maxExclusive)when you prefer explicit control over the exclusive upper limit.
Kotlin vs Ruby style
Ruby style:
rand(0..10)
Kotlin equivalent:
(0..10).random()
The ideas are similar: define a range, then pick a random value from it.
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.
Common patterns
val dice = (1..6).random()
val age = (18..65).random()
val item = listOf("a", "b", "c").random()
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()
Why am I not getting the maximum value with Random.nextInt()?
Because the second argument is excluded.
Random.nextInt(0, 10)
returns 0 through 9.
Can random numbers repeat in Kotlin?
Yes. Each random selection is independent unless you use logic to avoid duplicates.
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.
Add a Maven Repository URL in Gradle Kotlin DSL (build.gradle.kts)
Learn how to add Maven Central and a custom Maven repository URL in Gradle Kotlin DSL using build.gradle.kts syntax.
Allow HTTP and HTTPS in Android 9 Pie with Network Security Configuration
Learn how Android 9 Pie handles cleartext HTTP traffic and how to allow HTTP and HTTPS safely using network security config.