Random Numbers in Scala

Here’s the translation of the Go code example to Scala, formatted in Markdown suitable for Hugo:

import scala.util.Random

object RandomNumbers {
  def main(args: Array[String]): Unit = {
    // For example, `Random.nextInt(n)` returns a random `Int` i,
    // where 0 <= i < n.
    print(Random.nextInt(100) + ",")
    println(Random.nextInt(100))

    // `Random.nextDouble()` returns a `Double` d,
    // where 0.0 <= d < 1.0.
    println(Random.nextDouble())

    // This can be used to generate random doubles in
    // other ranges, for example 5.0 <= d' < 10.0.
    print((Random.nextDouble() * 5) + 5 + ",")
    println((Random.nextDouble() * 5) + 5)

    // If you want a known seed, create a new
    // Random instance with a specific seed.
    val r2 = new Random(42)
    print(r2.nextInt(100) + ",")
    println(r2.nextInt(100))

    val r3 = new Random(42)
    print(r3.nextInt(100) + ",")
    println(r3.nextInt(100))
  }
}

Scala’s scala.util.Random package provides pseudorandom number generation.

To run the program, save it as RandomNumbers.scala and use scala:

$ scala RandomNumbers.scala
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

Some of the generated numbers may be different when you run the sample.

Note that Scala’s Random class doesn’t have a direct equivalent to Go’s PCG (Permuted Congruential Generator). Instead, we’re using a simple seeded Random instance. The behavior might not be exactly the same as the Go example, but it demonstrates the concept of seeded random number generation.

See the scala.util.Random documentation for references on other random quantities that Scala can provide.