Upload
benoit-de-chateauvieux
View
1.216
Download
1
Tags:
Embed Size (px)
Citation preview
Hanoi JUG - 2015
Simple poll !
Who knows Java ?
Who knows Lambda ?
Who knows Functional Programming ?
Hanoi JUG - 2015
Why talking about Java 8 today ?
Java 7 End Of Public Updates = April 2015
https://plumbr.eu/blog/java/java-version-statistics-2015-edition
Hanoi JUG - 2015
What’s new in Java 8 ?
Java 8 (March 18, 2014):● JEP 126: Lambda & Stream
● JEP 174: Project Nashorn (JS in Java)
● JEP 104: Annotation on Java Types● Unsigned Integer Arithmetic● JEP 120: Repeating annotations● JEP 150: Date and Time API● JEP 178: Statically-linked JNI libraries● JEP 153: Launch JavaFX applications● JEP 122: Remove the permanent generation
JEP = JDK Enhancement Proposals
Hanoi JUG - 2015
Agenda
AGENDA
1. Basicsa. Lambdab. Functional Interfacec. Default & Static method
2. Built-in functionsa. Built-in functionsb. Composing functions
3. Lambda: Advanceda. Variable scopingb. Effectively finalc. Method reference
4. Summary
Hanoi JUG - 2015
Lambda in Java
Lambda expressions is the single largest upgrade to the programming model ever - larger even than generics.
This is the first time we have done a carefully coordinated co-evolution of the JVM, the language, and the libraries all together – and the results still feel like Java.
Mark Reinhold“Chief Architect of the Java Platform”https://blogs.oracle.com/java/entry/the_javaone_2013_technical_keynote
Hanoi JUG - 2015
So, what is lambda ?
Lambda comes from the Functional Programming:- Lambda Calcul by Alonzo Church in 1936- Lisp by John McCarthy in 1958- ….
Functional Programming1. Everything is a (mathematical) function
a. Pure functions (compute output from input → no side effect)b. First-class and higher-order functions. i.e. function that
i. takes one or more functions as an inputii. or outputs a function
2. Immutability3. Recursion (no loop but functions that call themselves)4. Lambda (anonymous functions)
Programming
Imperative
Declarative
Procedural (ex: Fortran, C)
Object Oriented (ex: Java, C++)
Logic (ex: Prolog)
Functional (ex: Haskell, Erlang)
Hanoi JUG - 2015
So, what is lambda ?
For usLambda == a piece of functionality
I will not detailFunctional Programming
in this presentationHey ! Opportunity for a future JUG meeting !
Any speaker ?
Hanoi JUG - 2015
Java 8: Lambdas
1. Basicsa. Lambdab. Functional Interfacec. Default & Static method
2. Built-in functionsa. Built-in functionsb. Composing functions
3. Lambda: Advanceda. Variable scopingb. Effectively finalc. Method reference
4. Summary
Hanoi JUG - 2015
Syntax
Without lambdanew SomeInterface() {
@Overridepublic SomeType someMethod(OtherType args) {
… body ...return result;
}}
Lambda(OtherType args) -> { … body … return result; }
Boilerplate code
Hanoi JUG - 2015
Type inferencing
Types in argument list can be omitted.Since there is only one method in the functional interface, the compiler knows the expected types of the params
Basic lambda(String firstName, String lastName) -> { return firstName + “ “ + lastName }
Lambda with type infering(firstName, lastName) -> { return firstName + “ “ + lastName }
Hanoi JUG - 2015
Implied return value
For body, if expression is used instead of block, this expression will be returned with no explicit “return” neededIf method is void, no value is returned
Basic lambda(firstName, lastName) -> { return firstName + “ “ + lastName }
Lambda with implied return value(firstName, lastName) -> { firstName + “ “ + lastName }
Hanoi JUG - 2015
Omitting parenthesis
If method takes a single parameter, parenthesis are optional
Basic lambda(firstName) -> { “First name: “ + firstName }
Lambda with implied return valuefirstName -> { “First name: “ + firstName }
Hanoi JUG - 2015
Summary: lambda makes the code shorter
Java 7taskList.execute(new Runnable() {
@Overridepublic void run() {
doSomething(arg);}
});
Java 8taskList.execute( () -> doSomething(arg) );
Hanoi JUG - 2015
Java 8: Lambdas
1. Basicsa. Lambdab. Functional Interfacec. Default & Static method
2. Built-in functionsa. Built-in functionsb. Composing functions
3. Lambda: Advanceda. Variable scopingb. Effectively finalc. Method reference
4. Summary
Hanoi JUG - 2015
Definition
A functional interface is a Java interface that lists only one method
declaration.
Previously, they were known as a Single Abstract Method type (SAM)
Hanoi JUG - 2015
@FunctionalInterface
Interfaces are same in Java 7 and Java 8Implementations of interfaces are also same in Java 7 and Java 8Code that call functional interface can use lambda or not
@FunctionalInterface is not required but expresses design intentFunctional interfaces can be verified at compile time
Hanoi JUG - 2015
Java 8: Lambdas
1. Basicsa. Lambdab. Functional Interfacec. Default & Static method
2. Built-in functionsa. Built-in functionsb. Composing functions
3. Lambda: Advanceda. Variable scopingb. Effectively finalc. Method reference
4. Summary
Hanoi JUG - 2015
Default & Static methods
Functional interfaces have 1 single abstract method (this is the method that the lambda specifies)
But interfaces in Java 8 can have default methods that● have bodies● are inherited
They also can have static methods
⇒ They are more like abstract classes⇒ We now have multiple inheritance of implementation in Java !
Hanoi JUG - 2015
Let’s code !
You can avoid writing your functional interface.Java 8 has Built-in functions in java.util.
function package
So, let’s code…
If you want to code with lambda you have to1. Write a functional interface (annotated or
not with @FunctionalInterface)2. Write a code that call this functional
interface
Hanoi JUG - 2015
Java 8: Lambdas
AGENDA
1. Basicsa. Lambdab. Functional Interfacec. Default & Static method
2. Built-in functionsa. Built-in functionsb. Composing functions
3. Lambda: Advanceda. Variable scopingb. Effectively finalc. Method reference
4. Summary
Hanoi JUG - 2015
Built-in functions
java.util.function package contains 43 general purpose functional interfaces.
4 families of functional interfaces
Those functions can be ● Simply Typed● Generic
Function takes arguments and return something
Predicate take arguments and return a boolean
Consumer take arguments and return void
Supplier take no argument and return something
Hanoi JUG - 2015
Simply Typed Building Blocks
Functional interfaces are named according to arguments and return value.
java.util.function package contains built-in functions for simples types (Boolean, Double, Int, Long).Some are ● Unary: one argument● Binary: two arguments
ex: IntPredicate (int in, boolean out) LongUnaryOperator(long in, long out) DoubleBinaryOperator(two doubles in, double out)
Hanoi JUG - 2015
Generic Building Blocks
java.util.function package also contains generic built-in functions:
● Function○ Function<T,R> : unary function from T to R○ BiFunction<T, U, R> : binary function from T and U to R○ DoubleFunction<R> : unary function from double to R○ ...
● Predicate○ Predicate<T> : unary function from T to boolean○ ...
● Consumer○ Consumer<T> : unary function from T to void○ ...
● Supplier○ Supplier<T> : unary function from void to T○ ...
Hanoi JUG - 2015
Example: Predicate
We’ll see in next presentation that getFirstMatchingActivity() can be written more elegantly with Stream
Hanoi JUG - 2015
Java 8: Lambdas
1. Basicsa. Lambdab. Functional Interfacec. Default & Static method
2. Built-in functionsa. Built-in functionsb. Composing functions
3. Lambda: Advanceda. Variable scopingb. Effectively finalc. Method reference
4. Summary
Hanoi JUG - 2015
Composing functions
Functional interfaces can be composed.Some examples:
● Function○ Function<V, R> compose(Function<? super V, ? extends T> before)○ Function<T, V> andThen(Function<? super R, ? extends V> after)○ Returns a composed Function that applies functions in sequence
● Predicate○ Predicate<T> negate()○ Predicate<T> and(Predicate<? super T> other)○ Predicate<T> or(Predicate<? super T> other)○ Compose predicates using boolean logic
● Consumer○ Consumer<T> andThen(Consumer<? super T> after)○ Returns a composed Consumer that performs operations in sequence
Hanoi JUG - 2015
Custom methods that return Lambdas
Custom methods can also return lambda.The method can use a parameter to generate the lambda.
Hanoi JUG - 2015
Java 8: Lambdas
AGENDA
1. Basicsa. Lambdab. Functional Interfacec. Default & Static method
2. Built-in functionsa. Built-in functionsb. Composing functions
3. Lambda: Advanceda. Variable scopingb. Effectively finalc. Method reference
4. Summary
Hanoi JUG - 2015
Variable scoping
Let’s go back to our Runnable implementations.Do you remember ?Those implementations are strictly equivalent….
Hanoi JUG - 2015
Variable scoping
Well… not totally equivalent !What happens if I introduce a local variable ?
Lambda does not introduce a new level of scoping● Lambda cannot introduce new variables with the same name as variables
in method that creates the lambda● “this” refers to the class the declare the lambda
Hanoi JUG - 2015
Java 8: Lambdas
1. Basicsa. Lambdab. Functional Interfacec. Default & Static method
2. Built-in functionsa. Built-in functionsb. Composing functions
3. Lambda: Advanceda. Variable scopingb. Effectively finalc. Method reference
4. Summary
Hanoi JUG - 2015
Final vs Effectively final variables
● Lambda can only refer to local variable declared as final● If a non-final local variable is never modified, the
compiler consider it as “effectively final”
Hanoi JUG - 2015
Final vs Effectively final variables
● This limitation does not apply to instance variables
Hanoi JUG - 2015
Java 8: Lambdas
1. Basicsa. Lambdab. Functional Interfacec. Default & Static method
2. Built-in functionsa. Built-in functionsb. Composing functions
3. Lambda: Advanceda. Variable scopingb. Effectively finalc. Method reference
4. Summary
Hanoi JUG - 2015
Method reference
If the function we want to use already has a name, we don’t have to write a lambda for it: we can just use the method name:● ClassName::staticMethodName● variable::instanceMethodeName● ClassName::new
Hanoi JUG - 2015
Java 8: Lambdas
AGENDA
1. Basicsa. Lambdab. Functional Interfacec. Default & Static method
2. Built-in functionsa. Built-in functionsb. Composing functions
3. Lambda: Advanceda. Variable scopingb. Effectively finalc. Method reference
4. Summary
Hanoi JUG - 2015
So… when to use lambda ?
Use Case #1Use it if you need a simple instance of a functional interface and you do not need a constructor, a named type, fields, or additional methods.
Benefits⇒ more concise, readable and succinct code⇒ compatible with old Java 7 interfaces⇒ shipped with prebuilt functional interfaces
Hanoi JUG - 2015
So… when to use lambda ?
… but the syntax is not the most important thing about lambda.
Hanoi JUG - 2015
So… when to use lambda ?
Use Case #2Use it if you are encapsulating a single unit of behavior that you want to pass to other code.
○ For example, you would use a lambda expression if you want a certain action performed on each element of a collection, when a process is completed, or when a process encounters an error.
Benefits⇒ Start thinking in functions⇒ avoid mutable states and thus locks⇒ limit side-effects (and thus, bugs !)⇒ design more composable and reusable API
Hanoi JUG - 2015
Paradigm shift
The really fundamental thingabout lambda expression
is the huge paradigm shift they imply.
… and learning a new language is relatively easy comparing to learning a new paradigm.
Hanoi JUG - 2015
Further readings
This presentation on Slideshare● http://www.slideshare.net/benoitdechateauvieux/hanoi-jug-java-8-lambdas-
47013698
The code of this presentation● https://github.com/benoitdechateauvieux/hanoi-jug-lambda
Further readings● https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html● http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-
QuickStart/index.html● http://www.slideshare.net/mariofusco/java-8-workshop● http://www.beyondjava.net/blog/java-8-functional-programming-language/● http://www.infoq.com/articles/How-Functional-is-Java-8