1. Overview

In this tutorial, we’ll see how we can generate a random number in Scala.

2. Generating a Random Number

There are a few different approaches for generating a random number in Scala.

2.1. Using Scala Random

The simplest is to use the scala.util.Random class:

scala> val rand = new scala.util.Random
val rand: scala.util.Random = scala.util.Random@1f992a3a

scala> rand.nextInt()
val res0: Int = -1865253155

scala> rand.nextInt()
val res1: Int = 2082034767

scala> rand.nextInt()
val res2: Int = 917778542

Besides the Random#nextInt() method, the class also provides methods for generating random Longs, Floats, and Doubles:

scala> rand.nextLong()
val res3: Long = 2354050450753819371

scala> rand.nextLong()
val res4: Long = 5785333334023919593

scala> rand.nextFloat()
val res5: Float = 0.26160038

scala> rand.nextFloat()
val res6: Float = 0.4815238

scala> rand.nextDouble()
val res7: Double = 0.6054005522642839

scala> rand.nextDouble()
val res8: Double = 0.6886139388758996

2.2. Defining a Specific Range

Most times, we want to limit the random values. So we need to define a range of possible values. This can easily be achieved using the previous Random#nextInt() method, as it has an override that defines an upper limit. When passed, the method will return a value between 0 (inclusive) and the specified value (exclusive):

scala> val rand = new scala.util.Random
val rand: scala.util.Random = scala.util.Random@433d9680

scala> rand.nextInt(10)
val res0: Int = 0

scala> rand.nextInt(10)
val res1: Int = 8

scala> rand.nextInt(5)
val res2: Int = 2

scala> rand.nextInt(5)
val res3: Int = 0

scala> rand.nextInt(50)
val res4: Int = 19

But this method uses a lower limit of 0. In case we want to define both lower and upper limits, we’ll need to use the Random#between method:

scala> rand.between(3, 15)
val res6: Int = 9

scala> rand.between(3, 15)
val res7: Int = 6

2.3. Using Java Random

One of the big advantages of Scala is its interoperability with Java. This means we can also make use of Java solutions for generating random numbers, which is very similar to the Scala approach:

scala> val rand = new java.util.Random()
val rand: java.util.Random = java.util.Random@4a013b23

scala> rand.nextInt()
val res0: Int = 1853747943

scala> rand.nextInt()
val res1: Int = -615065491

scala> rand.nextInt(10)
val res2: Int = 0

scala> rand.nextInt(10)
val res3: Int = 1

scala> rand.nextInt(10)
val res4: Int = 2

scala> rand.nextInt(10)
val res5: Int = 1

scala> rand.nextInt(10)
val res6: Int = 9

3. Conclusion

In this article, we saw how to generate random numbers using both Scala and Java solutions.

Comments are closed on this article!