上QQ阅读APP看书,第一时间看更新
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 sum = new SumFunction
def runOperation(f: (Int, Int) => Int, a: Int, b: Int): Int = f(a, b)
}
object FunctionObjects {
def main(args: Array[String]): Unit = {
val obj = new FunctionObjects
System.out.println(s"3 + 9 = ${obj.sum(3, 9)}")
System.out.println(s"Calling run operation: ${obj.
runOperation(obj.sum, 10, 20)}")
System.out.println(s"Using Math.max: ${obj.runOperation(Math.max,
10, 20)}")
}
}