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 17

Implicitly Surprising

The ability to create and pass around partially applied functions helps you to move from specific to more general and reusable functionality. Instead of a method that increments a value by two, for instance, we can write a more generally applicable add method and specialize it for our use case:

  def add(x: Int)(y: Int) = x + y
  def addTo2 = add(2) _
    scala> addTo2(3)
  res2: Int = 5

Scala also supports implicits, which, among other things, allows you to pick up arguments from the context rather than passing them explicitly to methods and functions.

How do these two play together? What is the result of executing the following code in the REPL?

  implicit val z1 = 2
  def add(x: Int)(y: Int)(implicit z: Int) = x + y + z ...

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