Java Lambdas and Closures

closures, java, java-8, lambda

Solution

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<String> 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.

Problem

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 `teamA` and `teamB` typed? 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?

Original source

Related problems