1 Object Functions {2 def main (args:array[string]) {3 //Local Functions4def localfun (msg:string) =println (msg)5Localfun ("Hi")6 7 //Function Object8var list = list (1, 2, 3)9List.foreach ((x:int) =println (x))TenList.foreach (x =println (x)) One List.foreach (println (_)) A List.foreach (println _) - List.foreach (println) - List.foreach (Localfun) the - //Partial application of a function to convert a function to a function object -var addXY5 = Add (_: int, _: int, 5) -println (AddXY5 (3, 4)) +var addfunobj =Add _ -println (Addfunobj (3, 4, 5)) + } A atdef add (X:int, Y:int, z:int): Int = { -X + y +Z - } -}
Nested methods, local methods, literal, but the compiler dynamically helped generate some anonymous classes, and the variables captured in closures are also members of these anonymous types. Focus on function object, similar to that. NET Delegate,function object literal is expressed as: (arguments list) = body, if the parameters in the method will only appear once, you can use the "_" syntax, that is: Do not use the parameter list, _ the order of the corresponding parameters.
How does the function convert to function object? This involves partial apply function, which is also very simple, for any function: func,func _ means that there is no parameter to apply, returning a function object with the same argument list as Func, You can also populate only some of the parameters as in the previous example.
If the signature of the required function object is consistent with the signature of the function, the compiler automatically applies the function part as a function object.
Scala:functions and Closures