Scala:functions and Closures

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.