3. Some history
You said lambda in java, but
● Smalltalk said block or closure
● C# said closure
● “Grubby” said closure
It's a block of code, that can be used a method
parameter, thread safe, and not wrapped in a class
So no more time waiting it in Java!
04/2013Ch. Huntzinger 3
4. What's that, lambda?
“In computer science, a closure (also lexical closure or
function closure) is a function or reference to a
function together with a referencing environment of
that function.
A closure—unlike a plain function pointer—allows a
function to access those non-local variables even
when invoked outside of its immediate lexical scope.”
From wikipedia
04/2013Ch. Huntzinger 4
5. How it could deserve
Explicit function in code,
provide function as method parameters,
manage better concurrency
04/2013Ch. Huntzinger 5
6. Some old battle
The three possible shape of lambda
● BGGA: Gilad Bracha, Neal Gafter, James Gosling, Peter von der Ahé
button.addActionListener(ActionEvent ev => {
// handle the event
});
● CICE: simplified inner classes
button.addActionListener(ActionListener(ActionEvent ev) {
// handle the event
});
● FCM: First Class Method
button.addActionListener(#(ActionEvent ev) {
// handle the event
});
04/2013Ch. Huntzinger 6
7. Your first lambda
Simple shape:
Argument List Body of closure
(int x, int y) -> x+y
Ch. Huntzinger
704/2013
Complex shape:
Argument List Body of closure: multi lines possible
(int x, int y) -> {System.err.println(x+”+”y);};
8. Lambda by sample
● Event
04/2013Ch. Huntzinger 8
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent e){
System.err.println(“clicked!”);
}
};
ActionListener al = (e) -> {System.err.println(“clicked!”);};
9. Lambda by sample
● Runnable
04/2013Ch. Huntzinger 9
Runnable r = new Runnable(){
public void run(){
System.err.println(“Hello world!”);
}
};
Runnable r = () -> {System.err.println(“Hello world!”);};
10. Lambda under the hood
● Interface & default, @FunctionalInterface
● Not only an Inner class in bytecode
04/2013Ch. Huntzinger 10
public class SimpleSample {
// Lambda Runnable
protected Runnable r2 = () -> {System.out.println("Hello world two!");}
}
SimpleSample
SimpleSample lambda$3
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V > Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
11. New API for lambda
● New Collection API: new method in
java.util.Map and java.util.List to use
closure new capabilities
● java.util.function: a set of interface for basic
closure instantiation. Create your owns!
● java.util.stream: a set of interface to process
object’s Stream.
04/2013Ch. Huntzinger 11
12. advantages
• More concise code
• Ease concurency
• Better API capabilities:
o Simplify Pipeline
o Simplify filtering
o Explicit functional code
04/2013Ch. Huntzinger 12