Lambdas have been introduced in Java 8 in a move to match the offer of prominent languages such as Python, HASKELL and C++. Many experts consider this incorporation of Lambdas as the biggest change that Java had ever to go through since its initial release.
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Lambda Expressions in Java: Functional Interfaces and Type Inference
1. LAMBDA
EXPRESSIONS IN JAVA
Prepared by Mahdi CHERIF COURSE ADVANCED TOPICS IN
PROGRAMMING LANGUAGES Lectured by prof. BETTI VENNERI
29/05/2019
Functional
interfaces and
Lambda typing in
Java
2. LAMBDA EXPRESSIONS IN JAVA
Advanced Topics in Programming languages-2019 Page 1
Contents
History of lambda Calculus introduction in Java...............................................................................................................2
Introduction ......................................................................................................................................................................3
Lambda formalization in Java ...........................................................................................................................................3
Functional interfaces.....................................................................................................................................................3
Case study.....................................................................................................................................................................4
Out of the box libraries.................................................................................................................................................6
Typing Lambda in Java and Type inference ......................................................................................................................7
Type checking of Lambda expression ...........................................................................................................................7
Type inference ..............................................................................................................................................................7
Final notes.........................................................................................................................................................................8
Lazy evaluation with Lambda expressions....................................................................................................................9
References ......................................................................................................................................................................10
3. LAMBDA EXPRESSIONS IN JAVA
History of lambda Calculus introduction in Java
The Lambda project was first proposed in 2009.
At the time Lambda expressions were supported in major programming languages but not in Java.
With the acquisition of Java by Oracle completed in January 27, 2010, the Lambda expressions project was set to
be part of the Java 7 released in July 2011 but finally the project went packaged in Java 8 released in March
2014.
Today, some analysts consider that Java 8 is the biggest change since the initiation of the Java language with
Lambda expressions considered to be the most important new feature of this version Lecture 2: Design and
Implementation of Lambda Expressions in Java 8.
Lambda expressions aim to guarantee behavior parametrization in computer code. Such a parametrization is
very helpful when requirements are frequently changing.
However, anonymous “inner” classes, introduced in Java 1.1, have already offered behavior parametrization but
they were not very readable as well as verbose and this has discouraged developers from using them.
Java decided at the end to follow a safe strategy and incorporated them like other programming languages.
4. LAMBDA EXPRESSIONS IN JAVA
Advanced Topics in Programming languages-2019 Page 3
Introduction
Similarly to anonymous classes, Lambda expressions allow passing methods as arguments to other methods.
Furthermore, Lambda expressions are:
Reusable
Compact
Turing complete
Parallelizable
Lambda formalization in Java
The syntax of a Lambda expression is as follows:
In Java 8, Lambda expression is written as
(Parameters) -> {Body;}
We note that:
A Lambda can have zero or many parameters separated by commas and their type can be explicitly declared or
inferred from the context
Parenthesis are optional for a single parameter
For a single statement body braces are optional
() expresses a Lambda that has zero parameters
ATTENTION: In java, Lambdas can be used only in the context of a functional interface. Therefore, in order to pass a
method, i.e., behavior as a parameter we have to use a functional interface.
Functional interfaces
Lambda in Java can be used only in the context of functional interfaces. Wherein the functional interface is expected
the Lambda expression, this definition of the Lambda serves as an inline implementation of the abstract method.
The entire expression results in an instance of the ‘real’ implementation of the functional interface.
A functional interface is an interface defining only one abstract method. The signature of the abstract method is
considered a description of the signature of the Lambda expression and is called the function descriptor.
A functional interface can have default methods, i.e., a method that is not abstract which defines default
implementation for the method in case it has not been implemented by a class.
A functional interface is a lambda expressions-preceding notion in Java and its use is not restricted to them.
5. LAMBDA EXPRESSIONS IN JAVA
Case study
Our Case: Juice factory
Suppose we have the classes fruit and juice.
Our Lambda can be:
1. (fruit orange)-> {juice Orangejuice=new juice("Orange");
/*Code for Making Orange Juice*/
return (Orangejuice);}
2. (fruit strawberry)-> {juice Strawberryjuice=new juice("Strawberry");
/*Code for Making Strawberry Juice*/
return (Strawberryjuice);}
Our invocation of the JuiceMaker method will then be parametrized with changing behavior for the Juice maker
machine, i.e., we will not need many juice machines, we need a single machine for all types of fruits but a machine
that requires as input, besides the fruit itself, the correct behavior to adopt for the specific fruit.
@FunctionalInterface
public interface JuiceMachine {
juice MakeJuice(fruit f);
}
But how the entire interface turns into real instantiated implementation and how its method is invoked?
We first create a static method:
public static juice JuiceMaker(JuiceMachine M) {
return M.MakeJuice(f2);
}
Finally, we proceed with Lambda expressions:
JuiceMaker((fruit orange)-> {juice Orangejuice=new juice("Orange");
/*Code for Making Orange Juice*/
return (Orangejuice);})
JuiceMaker((fruit strawberry)-> {juice Strawberryjuice=new juice("Strawberry");
/*Code for Making Strawberry Juice*/
return (Strawberryjuice);})
Now it is possible to reuse the JuiceMaker method and treat a fruit according to different Lambdas, i.e., processes of
juice making specific to the type of fruit, such as:
6. LAMBDA EXPRESSIONS IN JAVA
Advanced Topics in Programming languages-2019 Page 5
Kiwi, apples, pomegranate, etc.
In Java terms:
The invocation of the static method will create an instance of the functional interface.
The abstract method of the interface has its implementation offered by the Lambda expression inline passed
as a parameter for the static method.
Each Lambda corresponds to a different concrete behavior of the interface as specified by its abstract
method.
Hence, each time we write a Lambda expression we are creating a new instance of the functional interface and
executing a new behavior of the juice machine.
Thanks to Lambda, any function f of the form fruit -> juice can be passed as parameter because it matches the
signature of the abstract method of the functional interface.
First conclusion: Our code can take functions as arguments and in this case functions of the form:
f: fruit -> juice
Note: f implements a behaviour and f is passed as an argument. We obtain, Behaviour parameterization.
In practical terms and not Java terms we have created a Juice Machine that takes as input arguments the fruit as well
as the function f and renders a juice:
Juice Machine: (f, fruit) -> juice
Now, let us go one step further.
For a juice factory, there is an entire flow of different fruits which will of course produce an entire flow of different
types of juice.
For this we implement the Lambda expressions solution as follows:
public interface JuiceFactory <T, R>{
R MakeJuice(T t1);
}
Then, the functional interface is implemented.
fruit orange2=new fruit("Orange");
fruit pineapple=new fruit("Pineapple");
fruit apple=new fruit("Apple");
fruit cherry=new fruit("Cherry");
List <fruit> list5=Arrays.asList(orange2,pineapple,apple,cherry);
List <juice> juiceflow1=new ArrayList <juice>();
JuiceFactory <fruit, juice> jft1=((fruit fr1)-> {System.out.println("Fruit type:
"+fr1.get_fruit_type());
juice jce1=new juice(fr1.get_fruit_type());
/*Code for Making Strawberry Juice*/
return (jce1);});
juiceflow1=AnyJuiceAnyQuantityMaker(list5,jft1);
for (juice fg:juiceflow1)
{
System.out.println("Juice type: "+fg.get_juice_type());
}
Note:
T would typically be in this case any type of accepted fruits.
7. LAMBDA EXPRESSIONS IN JAVA
The factory can make as much quantity of juice and as many types as the supply chain allows it!
For the previous example and for a supply chain of an Orange, a Pineapple, an Apple and a Cherry,
we get this result of the compilation:
The flow of the factory is processed correctly and with one machine.
Out of the box libraries
The Java API offers several pre-defined functional interfaces, e.g., Predicate <T>, Consumer <T>, <Function>, etc.
These interfaces introduced in Java 8 cover common forms of functions and can be re-used to pass various types of
lambdas.
8. LAMBDA EXPRESSIONS IN JAVA
Advanced Topics in Programming languages-2019 Page 7
Typing Lambda in Java and Type inference
Although the Lambda expression offers an inline instantiation for an implementation of the functional interface it is
not explicitly linked to the interface it implements, i.e., the functional interface is not mentioned in the body of the
Lambda expression.
Type checking of Lambda expression
Java uses the notion of target type for the identification of the type of the Lambda expression. This target type is
recognized thanks to the expected parameter type if the Lambda is passed as an argument of a method or given the
type of the local variable it is assigned to. Java looks at the context and identifies the target type and consequently
the type of the Lambda expression. Additionally, Lambda expressions can get the target type from a cast context.
To summarize, the Lambda type is checked given the target type which can be recognized from the context whether
it is:
Method invocation context.
Assignment context.
Cast context.
Type inference
Given the target type java knows what functional interface to implement for each Lambda expression. As a result, it
can infer the types of the parameters of the Lambda expression, i.e., from the function descriptor or equally called
the signature of the functional interface. As a result, it is not necessary to explicit the types of the parameters of the
Lambda expression.
In fact, if we change our first example slightly such as the first lambda does not explicit the parameter type fruit
while we keep this type declaration for the second such as the code is:
juice jc1=new juice();
jc1.set_juice_type(
JuiceMaker((orange)-> {juice Orangejuice=new juice("Orange");
/*Code for Making Orange Juice*/
return (Orangejuice);})
);
juice jc2=new juice();
jc2.set_juice_type(
JuiceMaker((fruit strawberry)-> {juice Strawberryjuice=new juice("Strawberry");
/*Code for Making Strawberry Juice*/
return (Strawberryjuice);})
);
System.out.println(jc1.get_juice_type());
System.out.println(jc2.get_juice_type());
After running this piece of code, we can verify that indeed both Lambdas have been treated alike although for the
first Lambda, orange was not explicitly declared as of type fruit, to the contrary strawberry, in the second Lambda, is
explicitly declared as of type fruit:
9. LAMBDA EXPRESSIONS IN JAVA
But, as shown here both Lambdas have the same output.
Final notes
In mathematics and computer science, a higher-order function is a function that does at least one of the following:
Takes one or more functions as arguments, i.e., procedural parameters.
Returns a function as its result.
Lambda in java allows chaining and composing functions. The functional interface itself takes, as explained in our
case, a function as parameter, i.e., the function defined by the function signature.
Further to that, the pre-defined functional interface Function comes with two default methods for composing
functions, i.e., andThen and compose.
Functional interfaces such as Comparator, Predicate and Function come with different default methods that can be
used to combine Lambda expressions.
Additionally, the default methods of functional interfaces can be invoked on Lambda expressions. This increases the
possibilities of the Lambda expressions in Java.
In the next example, a functional interface with a function signature having a function from Integer to Integer as an
argument and a function from Integer to a function from Integer to Integer as returned type:
Function<Integer,Function<Integer, Integer> >
curryAdder = u -> v -> u + v;
The example can go further:
Function<Function<Integer, Integer>, Function<Integer, Integer>> twice = f ->
f.andThen(f);
twice.apply(x -> x + 3).apply(7); // 13
This is a kind of high-order for values only and not for the formal expression, i.e., the expression having only names
of functions and types of arguments. The evaluation of the high-order function occurs only once we get real
numbers.
In addition, we do not have an explicit arrow type.
10. LAMBDA EXPRESSIONS IN JAVA
Advanced Topics in Programming languages-2019 Page 9
Although, Lambda expressions in Java are created to be functions they are in fact objects, we are merely creating
objects, yet, in Lambda calculus those expressions are pure functions.
Somehow, there is an ‘attempt to simulate’ some aspects of the arrow type as well as higher-order calculus. Why
only an attempt? Why ‘simulate’ and not fully implement them?
First-order logic is not decidable in general, in particular, the set of logical validities in any signature that includes
equality and at least one other predicate with two or more arguments is not decidable. Logical systems extending
first-order logic, such as second-order logic and type theory, are also undecidable.
Lazy evaluation with Lambda expressions
The Java community considers that Lambda expressions can be harnessed for the purpose of lazy evaluation:
The Supplier interface introduced in Java 8 can be helpful for this aim. The interface has the function <T> get()
having no arguments and returns a result of type T:
Double d=/*Very long computation*/…; EAGER EVALUATION
Supplier <Double> d= ()->/*Very long computation*/…; LAZY EVALUATION
The long computation of the second line will be triggered only when the get() method is invoked.
Note: Streams, out of the scope of this presentation, introduced in Java 8 support the lazy evaluation for all
intermediate operations which all return a stream as a result, this allows for the intermediate operations to be
pipelined.
THANK YOU FOR YOUR ATTENTION
11. LAMBDA EXPRESSIONS IN JAVA
References
Aho, A. V. (n.d.). Lecture 2: Design and Implementation.
Changes for Java 1.1. (n.d.). Retrieved from https://www.cs.cornell.edu/andru/javaspec/1.1Update.html
Currying. (n.d.). Retrieved from https://en.wikipedia.org/wiki/Currying
Currying functions in java with examples. (n.d.). Retrieved from https://www.geeksforgeeks.org/currying-functions-
in-java-with-examples/
Decidability (logic). (n.d.). Retrieved from https://en.wikipedia.org/wiki/Decidability_(logic)
Does java have lazy evaluation. (n.d.). Retrieved from https://stackoverflow.com/questions/15189209/does-java-
have-lazy-evaluation
HEALTHY JUICE CLEANSE RECIPES. (n.d.). Retrieved from https://www.modernhoney.com/healthy-juice-cleanse-
recipes/
Higher order function. (n.d.). Retrieved from https://en.wikipedia.org/wiki/Higher-order_function
http://hashtagsyria.com/en/index.php/news/item/1334-a-new-official-move-to-establish-the-juice-factory-of-the-
coast-%E2%80%A6-the-perseverance-still-exists. (n.d.). Retrieved from
http://hashtagsyria.com/en/index.php/news/item/1334-a-new-official-move-to-establish-the-juice-factory-
of-the-coast-%E2%80%A6-the-perseverance-still-exists
Java version history. (n.d.). Retrieved from https://en.wikipedia.org/wiki/Java_version_history
Lambda calculus. (n.d.). Retrieved from https://en.wikipedia.org/wiki/Lambda_calculus
Lambda Expressions. (n.d.). Retrieved from
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Leveraging lambda expressions for lazy evaluation. (n.d.). Retrieved from https://dzone.com/articles/leveraging-
lambda-expressions-for-lazy-evaluation
LORENZO BETTINI, V. B.-C. (2018). JAVA & LAMBDA: A FEATHERWEIGHT STORY. Logical Methods in Computer
Science, 1–24.
Pierce, B. C. (n.d.). Types and Programming Languages. The MIT Press.
Project proposal: Lambda. (n.d.). Retrieved from http://mail.openjdk.java.net/pipermail/announce/2009-
December/000087.html
Raoul-Gabriel Urma, M. F. (n.d.). Java 8 in action. MANNING.
Simply typed lambda calculus. (n.d.). Retrieved from https://en.wikipedia.org/wiki/Simply_typed_lambda_calculus
Stream in Java. (n.d.). Retrieved from https://www.geeksforgeeks.org/stream-in-java/
Sun acquisition by Oracle. (n.d.). Retrieved from https://en.wikipedia.org/wiki/Sun_acquisition_by_Oracle
Supplier interface in java with examples. (n.d.). Retrieved from https://www.geeksforgeeks.org/supplier-interface-in-
java-with-examples/
The ? : operator in Java. (n.d.). Retrieved from http://www.cafeaulait.org/course/week2/43.html
The Basics of Java Generics. (n.d.). Retrieved from https://www.baeldung.com/java-generics
Venneri, B. (2018-2019). Lectures of Advanced topics in programming languages. Florence.
What does lambda with 2 arrows mean in java 8. (n.d.). Retrieved from
https://stackoverflow.com/questions/32820722/what-does-lambda-with-2-arrows-mean-in-java-8