Mirko Benedetti Mirko Benedetti - 1 year ago 86
Scala Question

Immutable Scala Collection

I have this Scala code that spits out unique random numbers for the Italian lottery:

object Enalotto {
def main(args: Array[String]): Unit = {
val numbers = scala.collection.mutable.SortedSet[Int]()
val r = scala.util.Random

while(numbers.size < 6) {
numbers += r.nextInt(90) + 1

for ((number, index) <- numbers.view.zipWithIndex) {
if(number < 10) print("0")
if(index < 5) print(" - ")


I would like to ask, how would you write the same program with an immutable collection, in a more appropriate functional-style programming?

Thanks in advance.

Answer Source
List.iterate(0,7)(_ => util.Random.nextInt(90) + 1)
  .map(n => if (n<10) 0 else n)
  .mkString(" - ")

This is your generator and your formatter.

Explanation: I'm calling the iterate() method of the List companion object. It creates a new List of 7 elements, starting with the value 0. For every value after that it invokes the anonymous function that generates a random value.

Now we have our list. Take the tail because we're actually not interested in the starting 0 value.

Use map to zero numbers less than 10, sort the result, and turn the List into a String with the elements separated by the string " - ".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download