Java Lambdas and Closures

后端 未结 3 937
星月不相逢
星月不相逢 2020-12-29 06:20

I hear lambdas are coming soon to a Java near you (J8). I found an example of what they will look like on some blog:

SoccerService soccerService = (teamA, te         


        
3条回答
  •  旧巷少年郎
    2020-12-29 06:25

    The Lambda expression is just syntactic sugar to implement a target interface, this means that you will be implementing a particular method in the interface through a lambda expression. The compiler can infer the types of the parameters in the interface and that's why you do not need to explicitly define them in the lambda expression.

    For instance:

    Comparator c = (s1, s2) -> s1.compareToIgnoreCase(s2);
    

    In this expression, the lambda expression evidently implements a Comparator of strings, therefore, this implies the lambda expression is syntactic sugar for implementing compare(String, String).

    Thus, the compiler can safely assume the type of s1 and s2 is String.

    Your target interface type provides all the information the compiler needs to determine what are the actual types of the lambda parameters.

    Briant Goetz, Java Language Architect at Oracle Corportion has published a couple of articles of the work in progress in JDK 8 Lambdas. I believe the answers to your questions are there:

    • State of Lambda.
    • State of Lambda Libraries Edition.
    • Translation of Lambda Expressions
    • JVMLS 2012: Implementing Lambda Expressions in Java

    This second article explains how the lambda expressions are implemented at the bytecode level and may help you delve into the details of your second question.

提交回复
热议问题