SlideShare ist ein Scribd-Unternehmen logo
1 von 11
Downloaden Sie, um offline zu lesen
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
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
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.
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.
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:
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.
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.
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:
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.
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

JavaScript for ABAP Programmers - 2/7 Data Types
JavaScript for ABAP Programmers - 2/7 Data TypesJavaScript for ABAP Programmers - 2/7 Data Types
JavaScript for ABAP Programmers - 2/7 Data TypesChris Whealy
 
JavaScript for ABAP Programmers - 7/7 Functional Programming
JavaScript for ABAP Programmers - 7/7 Functional ProgrammingJavaScript for ABAP Programmers - 7/7 Functional Programming
JavaScript for ABAP Programmers - 7/7 Functional ProgrammingChris Whealy
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhHarmeet Singh(Taara)
 
Lambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzLambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzJAX London
 
Eclipse and Java 8 - Eclipse Day India 2013
Eclipse and Java 8 - Eclipse Day India 2013Eclipse and Java 8 - Eclipse Day India 2013
Eclipse and Java 8 - Eclipse Day India 2013Noopur Gupta
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Harmeet Singh(Taara)
 
Java 8 - A step closer to Parallelism
Java 8 - A step closer to ParallelismJava 8 - A step closer to Parallelism
Java 8 - A step closer to Parallelismjbugkorea
 
Java modular extension for operator overloading
Java modular extension for operator overloadingJava modular extension for operator overloading
Java modular extension for operator overloadingijpla
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
candi-binding-tutorial
candi-binding-tutorialcandi-binding-tutorial
candi-binding-tutorialtutorialsruby
 
JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014Noopur Gupta
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8Takipi
 
Solutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchSolutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchAlbern9271
 
Generic UXD Legos - Selenium Conference 2015
Generic UXD Legos - Selenium Conference 2015Generic UXD Legos - Selenium Conference 2015
Generic UXD Legos - Selenium Conference 2015Selena Phillips
 

Was ist angesagt? (17)

JavaScript for ABAP Programmers - 2/7 Data Types
JavaScript for ABAP Programmers - 2/7 Data TypesJavaScript for ABAP Programmers - 2/7 Data Types
JavaScript for ABAP Programmers - 2/7 Data Types
 
JavaScript for ABAP Programmers - 7/7 Functional Programming
JavaScript for ABAP Programmers - 7/7 Functional ProgrammingJavaScript for ABAP Programmers - 7/7 Functional Programming
JavaScript for ABAP Programmers - 7/7 Functional Programming
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
 
Lambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzLambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian Goetz
 
Eclipse and Java 8 - Eclipse Day India 2013
Eclipse and Java 8 - Eclipse Day India 2013Eclipse and Java 8 - Eclipse Day India 2013
Eclipse and Java 8 - Eclipse Day India 2013
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
 
Java 8 - A step closer to Parallelism
Java 8 - A step closer to ParallelismJava 8 - A step closer to Parallelism
Java 8 - A step closer to Parallelism
 
Java modular extension for operator overloading
Java modular extension for operator overloadingJava modular extension for operator overloading
Java modular extension for operator overloading
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
candi-binding-tutorial
candi-binding-tutorialcandi-binding-tutorial
candi-binding-tutorial
 
JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 
Solutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchSolutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitch
 
Generic UXD Legos - Selenium Conference 2015
Generic UXD Legos - Selenium Conference 2015Generic UXD Legos - Selenium Conference 2015
Generic UXD Legos - Selenium Conference 2015
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Advanced soa and web services
Advanced soa and web servicesAdvanced soa and web services
Advanced soa and web services
 

Ähnlich wie Lambda Expressions in Java: Functional Interfaces and Type Inference

Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APIPrabu U
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An OverviewIndrajit Das
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closuresmelechi
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressionsLars Lemos
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programmingThang Mai
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdfHASENSEID
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogrammingLuis Atencio
 
Java8 training - Class 1
Java8 training  - Class 1Java8 training  - Class 1
Java8 training - Class 1Marut Singh
 
Bt0074 oops with java
Bt0074 oops with javaBt0074 oops with java
Bt0074 oops with javaTechglyphs
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2Techglyphs
 
Week-1..................................
Week-1..................................Week-1..................................
Week-1..................................kmjanani05
 
jBPM Overview & Alfresco Workflows
jBPM Overview &  Alfresco WorkflowsjBPM Overview &  Alfresco Workflows
jBPM Overview & Alfresco WorkflowsFrancesco Valente
 
Why Functional Programming So Hard?
Why Functional Programming So Hard?Why Functional Programming So Hard?
Why Functional Programming So Hard?Ilya Sidorov
 
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? reactima
 

Ähnlich wie Lambda Expressions in Java: Functional Interfaces and Type Inference (20)

Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream API
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closures
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressions
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdf
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
 
Java8 training - Class 1
Java8 training  - Class 1Java8 training  - Class 1
Java8 training - Class 1
 
Java 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENTJava 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENT
 
Bt0074 oops with java
Bt0074 oops with javaBt0074 oops with java
Bt0074 oops with java
 
Jsp tutorial
Jsp tutorialJsp tutorial
Jsp tutorial
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2
 
Week-1..................................
Week-1..................................Week-1..................................
Week-1..................................
 
jBPM Overview & Alfresco Workflows
jBPM Overview &  Alfresco WorkflowsjBPM Overview &  Alfresco Workflows
jBPM Overview & Alfresco Workflows
 
Why Functional Programming So Hard?
Why Functional Programming So Hard?Why Functional Programming So Hard?
Why Functional Programming So Hard?
 
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
 

Kürzlich hochgeladen

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Kürzlich hochgeladen (20)

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
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