Functions without syntactic sugar

In the preceding example, we just used syntactic sugar. In order to understand exactly what happens, we will show you what the function literals are converted into. They basically represent extensions to the FunctionN trait, where N is the number of parameters. The implementations of the literals are invoked using the apply method (whenever a class or an object has an apply method, it can be implicitly invoked just using parentheses after the object name or instance and passing the required parameters, if any). Let's see the equivalent implementation to our previous example:

class SumFunction extends Function2[Int, Int, Int] {  override def apply(v1: Int, v2: Int): Int = v1 + v2}class FunctionObjects { val ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.