Randoms in Kotlin

Somesh Kumar
3 min readNov 16, 2018

--

Remember, Java provides interesting ways to generate random numbers and Kotlin is no different. Until recently Kotlin didn’t have its own Random class but with the release of Kotlin 1.3 developers now have a whole new kotlin.random package so let’s see how it’s done !! There are 4 (or more) ways to do it-

  • Using kotlin.random package (Only for Kotlin 1.3 or above)
  • Using Kotlin shuffled() function on Ranges (For Kotlin 1.2)
  • Using java.util.Random()
  • Using ThreadLocalRandom class (Only for Java 1.7 or above)

Let’s look at them one by one -

Using Random class (Kotlin 1.3)

Kotlin is a multiplatform language and there was no common API to generate random number in Kotlin for all targets, there was no way to do that consistently in multiplatform code. As of 1.3, Kotlin comes with its own multiplatform Random generator. You can now do the following (source):

var ran = Random.nextInt(0, 10) // will give integer between 0 & 9

using extension functions we can make it even better

fun IntRange.random(): Int = Random.nextInt(start, endInclusive + 1)

and simply use it directly with kotlin ranges like

val ran = (0..10).random() // random integer between 0 & 10
val anotherRan = (0 until 10).random() // random between 0 & 9¼

Edit: Kotlin already has an extension function for this in version 1.3 in its standard library which we can use exactly as mentioned above.

Using Kotlin shuffled() function on Ranges (Kotlin 1.2)

For those people who are stuck in the past (Kotlin 1.2) for some reason, there is a way to generate random numbers in pure kotlin way without using any java import.
Just create a close range and shuffle it and pick the first value as first() will return the first value in range after shuffling.

val someInt = (1..100).shuffled().first() // or .last() doesn't matter

Just be aware it’s big O(n), but for a small list it’s alright

Using Java’s Random class

var oldRand = Random().nextInt(100) // import java.util.Random

if we use Kotlin extension function then we can write it as

// Kotlin Extension function using Java Random class
fun IntRange.random() = Random().nextInt((endInclusive + 1) - start) + start

and use it with range

var rand = (5..50).random() // will give random between 5 and 50

Using ThreadLocalRandom

We can also use java.util.concurrent.ThreadLocalRandom to generate a random double, integer or long value and they can be both positive or negative.

ThreadLocalRandom is thread-safe and provides better performance in a multithreaded environment because it provides a separate Random object for every thread and thus reduces contention between threads.
Use of ThreadLocalRandom is particularly appropriate when multiple tasks use random numbers in parallel.

val safeRand= ThreadLocalRandom.current().nextInt(0, 100) // will give random between 0 to 99

Just be aware ThreadLocalRandom is only available @since Java 1.7 😉

--

--