To generate a random number in Kotlin, use kotlin.random.Random.Default.nextInt() for integers, nextDouble() for doubles, or nextFloat() for floats. For a specific range, call Random.nextInt(from, until) (exclusive upper bound) or Random.nextInt(from..until) (inclusive upper bound).
Background: Kotlin’s Random API
Kotlin provides a built-in kotlin.random.Random object, introduced in Kotlin 1.3, that wraps platform-specific random generators. On the JVM, it uses java.util.Random; on Android, it uses the same JVM implementation; on Kotlin/Native and Kotlin/JS, it uses the platform’s native random source. This means you don’t need any external libraries for basic random number generation. The Random object is thread-safe and can be used directly, or you can create your own instance with Random(seed) for reproducible sequences.
How to Generate Random Integers
The most common task is generating a random integer. Here are the core methods:
Random.nextInt()– returns a randomIntfromInt.MIN_VALUEtoInt.MAX_VALUE(inclusive).Random.nextInt(until)– returns a randomIntfrom 0 (inclusive) tountil(exclusive). For example,Random.nextInt(10)gives 0–9.Random.nextInt(from, until)– returns a randomIntfromfrom(inclusive) tountil(exclusive). Example:Random.nextInt(5, 15)gives 5–14.Random.nextInt(from..until)– uses aIntRangeand returns a value fromfromtountilinclusive. Example:Random.nextInt(5..15)gives 5–15.
Here’s a complete example:
import kotlin.random.Random
fun main() {
val randomInt = Random.nextInt(1, 101) // 1..100
println(randomInt)
}
Note that the range version with .. is inclusive, while the two-argument version is exclusive of the upper bound. This is a common source of off-by-one errors.
Generating Random Doubles, Floats, and Longs
For floating-point numbers, Kotlin offers:
Random.nextDouble()– returns aDoublebetween 0.0 (inclusive) and 1.0 (exclusive).Random.nextDouble(from, until)– returns aDoublefromfrom(inclusive) tountil(exclusive).Random.nextFloat()– returns aFloatbetween 0.0f and 1.0f (exclusive).Random.nextLong()– returns a randomLong.Random.nextLong(until)andRandom.nextLong(from, until)– similar to integers but forLong.
Example for a double in a range:
val randomDouble = Random.nextDouble(10.0, 20.0) // 10.0 to 19.999...
println(randomDouble)
For floats, note that Random.nextFloat() does not have a range overload; you must scale it manually: Random.nextFloat() * (max - min) + min.
How to Choose a Random Element from a Collection
Often you need a random item from a list or array. Kotlin provides extension functions:
list.random()– returns a random element from a collection.list.randomOrNull()– returns a random element ornullif the collection is empty.array.random()– works on arrays.
Example:
val fruits = listOf("apple", "banana", "cherry")
val randomFruit = fruits.random()
println(randomFruit)
These functions internally use Random.Default. If you need a seeded random selection, you can pass a Random instance: fruits.random(random).
Seeding the Random Generator for Reproducibility
Sometimes you want the same sequence of random numbers, for testing or procedural generation. You can create a Random instance with a seed:
val seededRandom = Random(42)
val first = seededRandom.nextInt(100)
val second = seededRandom.nextInt(100)
println("$first $second") // Same values every run
Using the same seed produces the same sequence. Without a seed, Random.Default uses a random seed based on the system time, so each run differs. Note that Random(seed) is deterministic across runs on the same platform, but the exact sequence may differ between JVM and Native, so don’t rely on it for cross-platform persistence.
Common Pitfalls and Misconceptions
One common mistake is using Random.nextInt(10) expecting 1–10, but it actually returns 0–9. Another is assuming Random.nextInt(1, 10) includes 10, but it doesn’t. To get 1–10 inclusive, use Random.nextInt(1, 11) or Random.nextInt(1..10).
Another misconception is that Random is cryptographically secure. It is not. For security-sensitive contexts (passwords, tokens, encryption), use java.security.SecureRandom on the JVM or kotlin.random.Random is not sufficient. On Android, you can use java.security.SecureRandom as well. Kotlin does not provide a built-in secure random, but you can call SecureRandom().nextInt().
Also, be careful with thread safety: Random.Default is thread-safe, but if you create your own Random instance and share it across threads, you should synchronize access or use ThreadLocalRandom (Java) if needed.
Performance and Alternatives
For most applications, Random.Default is fast enough. If you need high-throughput random numbers in a tight loop, consider using java.util.concurrent.ThreadLocalRandom (on JVM) to avoid contention. For cryptographic randomness, use SecureRandom. For generating random numbers in a range without creating many objects, the built-in functions are efficient.
If you need random numbers in Kotlin/JS, Random works fine, but the underlying generator may differ. For reproducible cross-platform sequences, you could implement your own PRNG, but that’s rarely necessary.
Frequently Asked Questions
How do I generate a random number between 1 and 10 inclusive in Kotlin?
Use Random.nextInt(1, 11) or Random.nextInt(1..10). The first argument is inclusive, the second is exclusive, so 11 is not included. The range version with .. includes 10.
Can I generate a random boolean in Kotlin?
Yes, use Random.nextBoolean(). It returns true or false with roughly equal probability.
How do I generate a random number with a fixed seed?
Create a Random instance with a seed: val r = Random(1234), then call methods on r. This gives reproducible sequences.
Is Kotlin’s Random cryptographically secure?
No. It’s a pseudo-random generator suitable for simulations, games, and non-security purposes. For secure randomness, use java.security.SecureRandom on the JVM or Android.
How do I get a random element from a list without repetition?
You can shuffle the list and take the first element: val shuffled = list.shuffled() then shuffled.first(). Or use list.random() repeatedly, but that may repeat. For sampling without replacement, use list.shuffled().take(n).
What’s the difference between Random.nextInt(10) and Random.nextInt(0, 10)?
They are identical: both return a random integer from 0 (inclusive) to 10 (exclusive). The single-argument version is just a shorthand for nextInt(0, until).
Related
- JD for Data Entry: What It Really Means
- How to Convert Text to Numbers in Excel
- COUPDAYBS in Google Sheets: How It Works
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Personal Budget Spreadsheet: How to Build OneA personal budget spreadsheet is a worksheet for listing income, planning expenses, and comparing your plan with what…
- Company Invoice Template in Excel: Setup and TipsYes. You can make a reusable company invoice template in Excel by laying out your business and customer…
- How to Capitalize All in Excel: 4 Quick WaysTo capitalize all letters in Excel, use the UPPER function: in a blank cell, type =UPPER(A1) (where A1…
- Excel Protected Sheet Unlock Online Free: Safe MethodsSometimes: a free online editor or unlocking service may remove worksheet protection, but it cannot reliably unlock every…
- Excel MAXIFS: Find the Highest Value for Each DateYes. In Excel, use MAXIFS to return the largest value from rows whose date matches a chosen date.…
- Excel Flash Fill for Workdays: What It Can and Can’t DoNo—not for reliable workday calculations. Excel Flash Fill can copy a pattern, such as turning dates into weekday…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.