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 25

Type Extortion

Many methods in the Scala collections library have a return type of Option, indicating they may fail to deliver a value. The recommended way to extract the value out of an Option is via the getOrElse method, which allows you to provide a default value in case the Option is empty.

The following program shows an example of getOrElse in action. What does it do?

  val zippedLists = (List(1,3,5), List(2,4,6)).zipped
  val (x, y) = zippedLists.find(_._1 > 10).getOrElse(10)
    println(s"Found $x")

Possibilities

  1. Prints:
      Found 10
    
  2. Prints:
      Found ()
    
  3. Fails to compile.
  4. Throws a runtime exception.

Explanation

Before trying to understand what is going on here, it is useful to quickly recap the behavior of zipped via a short example: ...

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