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, teamB) -> {
SoccerResult result = null;
if (teamA == teamB) {
result = SoccerResult.DRAW;
}
else if(teamA < teamB) {
result = SoccerResult.LOST;
}
else {
result = SoccerResult.WON;
}
return result;
};
So right off the bat:
- Where are
teamAandteamBtyped? Or aren’t they (like some weird form of generics)? - Is a lambda a type of closure, or is it the other way around?
- What benefits will this give me over a typical anonymous function?
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:
In this expression, the lambda expression evidently implements a
Comparatorof strings, therefore, this implies the lambda expression is syntactic sugar for implementingcompare(String, String).Thus, the compiler can safely assume the type of
s1ands2isString.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:
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.