O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Puzzler 32

Set the Record Straight

The Scala collections library provides convenience methods, such as toMap, toList, etc., that allow easy conversion between different collection types. The following program shows one of these in action. What does it do?

  val numbers = List("1""2").toSet() + "3"
  println(numbers)

Possibilities

  1. Prints:
      Set(1, 2, 3)
    
  2. Fails to compile.
  3. Prints:
      false3
    
  4. Prints:
      123
    

Explanation

The candidate answer that looks most probable is perhaps the first one:

  Set(1, 2, 3)

And that would indeed be the correct answer if the first line were:

  val numbers = List("1""2").toSet + "3"

However, the original program produces an entirely different result.

  scala> val numbers = List("1""2").toSet() + "3"
  numbers: String = false3 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required