SlideShare une entreprise Scribd logo
1  sur  61
Les lambda arrivent!
En attendant, êtes-vous sûr d'avoir
compris les génériques?
Henri Tremblay
Architecte Senior
OCTO Technology

@henri_tremblay
27 au 29 mars 2013
Les lambda arrivent!
En attendant, êtes-vous sûr d'avoir
compris les génériques?
Henri Tremblay
Architecte Senior
OCTO Technology

@henri_tremblay
27 au 29 mars 2013
Henri Tremblay
OCTO Technology
Responsable R&D
Performance
Calcul parallèle

Open Source
EasyMock
Objenesis
September 2013
September 2013
March 2014
March 2014
September 2004
Lambda

return Tweet.TWEETS.stream()
.collect(Collectors
.partitioningBy(
t->t.containsHashTag("#lambda")));
Lambda = Fun with generics
Stream<Tweet> stream = Tweet.TWEETS.stream();
Predicate<Tweet> lambda = t -> t.containsHashTag("#lambda");
Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector =
Collectors.partitioningBy(lambda);

return stream.collect(collector);
Lambda = Fun with generics
Stream<Tweet> stream = Tweet.TWEETS.stream();
Function<Tweet, Boolean> lambda = t -> t.containsHashTag("#lambda");
Collector<Tweet, Map<Boolean, List<Tweet>>> collector =
Collectors.<Tweet, Boolean, List<Tweet>, Map<Boolean, List<Tweet>>>
groupingBy(lambda, HashMap::new, ArrayList::new);
return stream.collect(collector);
What do I need to know?
Why

© OCTO 2011

12
What do I need to know?
Why

Covariance

© OCTO 2011

13
What do I need to know?
Why

Covariance
Capture

© OCTO 2011

14
What do I need to know?
Why

Covariance
Capture
Inference
© OCTO 2011

15
What do I need to know?
Why

Covariance
Capture
Inference
Erasure
© OCTO 2011

16
What do I need to know?
Why

Covariance

Capture

Erasure
© OCTO 2011

Inference

Bridge
17
Faire compiler

18
Dreaded warnings
Type safety: The expression of type List needs
unchecked conversion to conform to List<String>

Type safety: Unchecked cast from
List<capture#1-of ?> to List<String>
19
Ostrich defense
@SuppressWarnings("unchecked")

20
Why

© OCTO 2011

21

27 au 29 mars 2013
Rule #1

A code compiling
without warning should
never ever cause a
ClassCastException
22
Covariance

23

27 au 29 mars 2013
Arrays
Arrays are covariant:
Number n = Integer.MAX_VALUE;
Number[] list = new Integer[0];
Generics are not:
List<Number> l =

new ArrayList<Integer>(); // Illegal

24
Why not?
List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal
ln.add(new Float(3.1415));
int i = li.get(0); // ClassCastException

Would work if covariant

And allow to break rule #1

25
Why for array?
Integer[] list = // ...
foo(list);

public void foo(Object[] o) {
// ...
}
Arrays and generics don’t mix well
Can’t have an array of generics
List<String>[] lsa = new List<String>[10];// illegal

27
Because
If it was allowed
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK (covariant)
oa[0] = new ArrayList<Integer>(); // OK
String s = lsa[0].get(0); // bad

28
Exception

List<?>[] l = new ArrayList<?>[3];

29
Capture

30

27 au 29 mars 2013
Capture usually is
Type
List<?> bar();
<T> IExpectationSetters<T> expect(T value);
void andReturn(T value); // Method of IExpectationSetters
expect(bar()).andReturn(new ArrayList<String>());

And you get
The method andReturn(List<capture#6-of ?>) in the type
IExpectationSetters<List<capture#6-of ?>> is not applicable for the arguments
(ArrayList<String>)
31
Detail
List<?> bar();
<T> IExpectationSetters<T> expect(T value);
void andReturn(T value);
expect(bar()).andReturn(new ArrayList<String>());
List<Capture#6> bar = bar();
IExpectationSetters<List<Capture#6>> es =
expect(bar());
es.andReturn(List<Capture#6> value);
32
Only solution
We need to cast
expect((List<String>) bar()).andReturn(new
Tell to expect we want a
ArrayList<String>());
List<String>

But still a warning
Type safety: Unchecked cast from List<capture#6-of ?> to
List<String>
Framework coder tip:
Try to never return a wildcard unless necessary
33
Inference

34
Diamonds are a programmer best friend
List<String> l = new ArrayList<>();
How the compiler tells the type
Determine
the return
value type

The parameter

<T> T anyObject(T clazz)

36
How the compiler tells the type
The assigned
variable

Determine the
return type

MyType var = <T> T anyObject()

37
But watch out with overloading
public void foo(String s)
public void foo(Object o)

foo(anyObject());
Can’t
guess the
type
38
Trick #1
Determine the return
value type

Artificially give the type with a
dedicated parameter

<T> T anyObject(Class<T> clazz)

39
But how to pass a generic?
public void foo(String s)
public void foo(Object o)

foo(anyObject(List<String>.class));

Illegal
40
Some solutions
This would work

foo((String) anyObject());
foo((List<String>) anyObject()); // Warning
But still doesn’t work for
generics
41
Trick #2
So the only solution is
foo(EasyMock.<List<String>> anyObject());

… which sadly doesn’t support static imports
foo(.<List<String>> anyObject()); // Illegal

42
Trick #2 applied to Lambda
Return type: Map<Boolean, List<Tweet>>
return Tweet.TWEETS.stream()
.collect( Collectors.<Tweet, Boolean,
List<Tweet>, Map<Boolean, List<Tweet>>>
groupingBy(t->t.containsHashTag("#lambda"),
HashMap::new, ArrayList::new));
Lambda = Inference
return Tweet.TWEETS.stream()
.collect(Collectors
.partitioningBy(
t->t.containsHashTag("#lambda"));
How did he do it?
List<Tweet> list = Tweet.TWEETS;
Stream<Tweet> stream = list.stream();
R result = stream.collect(Collector<? super T, ?, R> collector);
R result = stream.collect(Collector<? super Tweet, ?, R> collector);
Collector<T, ?, Map<Boolean, List<T>>> collector =
Collectors.partitioningBy(Predicate<? super T> predicate);
Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector =
Collectors.partitioningBy(Predicate<? super Tweet> predicate);
Map<Boolean, List<Tweet>> result = stream.collect(Collector<? super Tweet, ?,
Map<Boolean, List<Tweet>>> collector);
Predicate<? super Tweet> lambda = (Tweet t) -> t.containsHashTag("#lambda");
Trick #3: Lambda inference

Object o = (Runnable) () -> {
System.out.println("hi");
};

Collections.sort(strings,
(String a, String b) -> a.compareTo(b));
Erasure

47
Erasure…
public void foo() {
List<String> l = new ArrayList<String>();

for (String s : l) {

No type

System.out.println(s);
}

public void foo() {

}

List l = new ArrayList();
for (String s : l) {

System.out.println(s);

Compilation

}
}
… or not erasure
public class A extends ArrayList<String> {}

public static void main(final String[] args) {
ParameterizedType type = (ParameterizedType)
A.class.getGenericSuperclass();
System.out.println(
type.getActualTypeArguments()[0]);
}

 prints class java.lang.String
49
Type class
java.lang.reflect.Type
•
•
•
•
•

GenericArrayType
ParameterizedType
TypeVariable
WildcardType
Implemented by Class

New powers unleashed!

java.lang.reflect.GenericDeclaration
Implemented by Class, Method, Constructor
50
Useful!
class A {}

abstract class BaseDao<T> {
public T load(final long id) {
// …
}
}
class ADao extends BaseDao<A> {}
© OCTO 2011

51
Useful!
@SuppressWarnings("unchecked")
public T load(final long id) {
ParameterizedType type =
(ParameterizedType) getClass()
.getGenericSuperclass();

ADao

BaseDao<A>

A

Type actualType = type.getActualTypeArguments()[0];
return em.find((Class<T>) actualType, (Long) id);
}

Unsafe cast
Bridge

© OCTO 2011

53
Everything seems normal…
class A<T> {
abstract void set(T value);
}
class B extends A<String> {
String value;
@Override
void set(final String value) {
this.value = value;
}
}
But is not
class B extends A {
void set(String value) {
this.value = value;
}
volatile void set(Object o){
set((String)o);
}

}
Example
Raw type warning

Perfectly compiling

A a = new B();
a.set(new Object());
But at runtime:
java.lang.ClassCastException
The actual problem being
B.class.getDeclaredMethods()
This

Returns that

volatile void set(java.lang.Object)
void B.set(java.lang.String)
And gives you no way to find out
which method is bridged
What about lambdas?
public class A {
public static void main(String[] args) {
Method[] methods = A.class.getDeclaredMethods();
Arrays.stream(methods).forEach(m ->
System.out.println(m + " "
+ m.isBridge() + " " + m.isSynthetic()));
}
}
Prints this
public static void A.main(java.lang.String[]) false false

private static void A.lambda$0(java.lang.reflect.Method) false true
Conclusion

Who has learned
something today?

© OCTO 2011

59
Useful links
Nice lambda tutorial (in French):
http://lambda.ninjackaton.ninja-squad.com/

Description of inference types on lambda:
http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html

Everything on generics:
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
Conclusion

Questions?

http://perfug.github.io/

+Henri
@henritremblay
htr@octo.com
© OCTO 2011

http://brownbaglunch.fr
61

Contenu connexe

Tendances

Core csharp and net quick reference
Core csharp and net quick referenceCore csharp and net quick reference
Core csharp and net quick referenceilesh raval
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to ImmutabilityKevlin Henney
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Programming Paradigms Which One Is The Best?
Programming Paradigms Which One Is The Best?Programming Paradigms Which One Is The Best?
Programming Paradigms Which One Is The Best?Netguru
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
Seductions of Scala
Seductions of ScalaSeductions of Scala
Seductions of ScalaDean Wampler
 

Tendances (20)

Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Lec4
Lec4Lec4
Lec4
 
Core csharp and net quick reference
Core csharp and net quick referenceCore csharp and net quick reference
Core csharp and net quick reference
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
ALF 5 - Parser Top-Down
ALF 5 - Parser Top-DownALF 5 - Parser Top-Down
ALF 5 - Parser Top-Down
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Lec2
Lec2Lec2
Lec2
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Programming Paradigms Which One Is The Best?
Programming Paradigms Which One Is The Best?Programming Paradigms Which One Is The Best?
Programming Paradigms Which One Is The Best?
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Seductions of Scala
Seductions of ScalaSeductions of Scala
Seductions of Scala
 
Fun with Kotlin
Fun with KotlinFun with Kotlin
Fun with Kotlin
 
Haskell
HaskellHaskell
Haskell
 
Lec2
Lec2Lec2
Lec2
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 

En vedette

Microbenchmarking with JMH
Microbenchmarking with JMHMicrobenchmarking with JMH
Microbenchmarking with JMHHenri Tremblay
 
Economical Sodium Ion Concentration Meter by ACMAS Technologies Pvt Ltd.
Economical Sodium Ion Concentration Meter by ACMAS Technologies Pvt Ltd.Economical Sodium Ion Concentration Meter by ACMAS Technologies Pvt Ltd.
Economical Sodium Ion Concentration Meter by ACMAS Technologies Pvt Ltd.Acmas Technologies Pvt. Ltd.
 
Конвейерное производство приложений
Конвейерное производство приложенийКонвейерное производство приложений
Конвейерное производство приложенийRambler Android
 
Reklamok Ertelmezese 2
Reklamok Ertelmezese 2Reklamok Ertelmezese 2
Reklamok Ertelmezese 2Zoltan Havasi
 
Seismic performance of a rc frame with soft storey criteria
Seismic performance of a rc frame with soft storey criteriaSeismic performance of a rc frame with soft storey criteria
Seismic performance of a rc frame with soft storey criteriaeSAT Journals
 
基礎から学ぶ組み込みAndroid
基礎から学ぶ組み込みAndroid基礎から学ぶ組み込みAndroid
基礎から学ぶ組み込みAndroiddemuyan
 
Google Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleGoogle Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleMathias Seguy
 
Reklamok Ertelmezese felkeszules a vizsgara
Reklamok Ertelmezese felkeszules a vizsgaraReklamok Ertelmezese felkeszules a vizsgara
Reklamok Ertelmezese felkeszules a vizsgaraZoltan Havasi
 
Animate me, If you don't do it for me do it for Chet :)
Animate me, If you don't do it for me do it for Chet :)Animate me, If you don't do it for me do it for Chet :)
Animate me, If you don't do it for me do it for Chet :)Mathias Seguy
 
Lec.6 strength design method rectangular sections 2
Lec.6   strength design method rectangular sections  2Lec.6   strength design method rectangular sections  2
Lec.6 strength design method rectangular sections 2Muthanna Abbu
 
Vernacular Architecture of Central india
Vernacular Architecture of Central indiaVernacular Architecture of Central india
Vernacular Architecture of Central indiaJulian_Divakar
 
JULIANA_BACCHUS_RESUME 2015
JULIANA_BACCHUS_RESUME 2015JULIANA_BACCHUS_RESUME 2015
JULIANA_BACCHUS_RESUME 2015Juliana Bacchus
 
Why Visual Content is Key for Oil & Gas Communications - Bill Roth [Energy Di...
Why Visual Content is Key for Oil & Gas Communications - Bill Roth [Energy Di...Why Visual Content is Key for Oil & Gas Communications - Bill Roth [Energy Di...
Why Visual Content is Key for Oil & Gas Communications - Bill Roth [Energy Di...Energy Digital Summit
 
Brands & Publishers: A Symbiotic Relationship for the Digital Age - Stacy Mar...
Brands & Publishers: A Symbiotic Relationship for the Digital Age - Stacy Mar...Brands & Publishers: A Symbiotic Relationship for the Digital Age - Stacy Mar...
Brands & Publishers: A Symbiotic Relationship for the Digital Age - Stacy Mar...Energy Digital Summit
 
Personal Branding: Career Management Strategies - Chris Westfall [Energy Digi...
Personal Branding: Career Management Strategies - Chris Westfall [Energy Digi...Personal Branding: Career Management Strategies - Chris Westfall [Energy Digi...
Personal Branding: Career Management Strategies - Chris Westfall [Energy Digi...Energy Digital Summit
 

En vedette (17)

Microbenchmarking with JMH
Microbenchmarking with JMHMicrobenchmarking with JMH
Microbenchmarking with JMH
 
Resume_RajeeshunArudchelvam_ver2
Resume_RajeeshunArudchelvam_ver2Resume_RajeeshunArudchelvam_ver2
Resume_RajeeshunArudchelvam_ver2
 
Economical Sodium Ion Concentration Meter by ACMAS Technologies Pvt Ltd.
Economical Sodium Ion Concentration Meter by ACMAS Technologies Pvt Ltd.Economical Sodium Ion Concentration Meter by ACMAS Technologies Pvt Ltd.
Economical Sodium Ion Concentration Meter by ACMAS Technologies Pvt Ltd.
 
Конвейерное производство приложений
Конвейерное производство приложенийКонвейерное производство приложений
Конвейерное производство приложений
 
Presentation
PresentationPresentation
Presentation
 
Reklamok Ertelmezese 2
Reklamok Ertelmezese 2Reklamok Ertelmezese 2
Reklamok Ertelmezese 2
 
Seismic performance of a rc frame with soft storey criteria
Seismic performance of a rc frame with soft storey criteriaSeismic performance of a rc frame with soft storey criteria
Seismic performance of a rc frame with soft storey criteria
 
基礎から学ぶ組み込みAndroid
基礎から学ぶ組み込みAndroid基礎から学ぶ組み込みAndroid
基礎から学ぶ組み込みAndroid
 
Google Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleGoogle Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification Google
 
Reklamok Ertelmezese felkeszules a vizsgara
Reklamok Ertelmezese felkeszules a vizsgaraReklamok Ertelmezese felkeszules a vizsgara
Reklamok Ertelmezese felkeszules a vizsgara
 
Animate me, If you don't do it for me do it for Chet :)
Animate me, If you don't do it for me do it for Chet :)Animate me, If you don't do it for me do it for Chet :)
Animate me, If you don't do it for me do it for Chet :)
 
Lec.6 strength design method rectangular sections 2
Lec.6   strength design method rectangular sections  2Lec.6   strength design method rectangular sections  2
Lec.6 strength design method rectangular sections 2
 
Vernacular Architecture of Central india
Vernacular Architecture of Central indiaVernacular Architecture of Central india
Vernacular Architecture of Central india
 
JULIANA_BACCHUS_RESUME 2015
JULIANA_BACCHUS_RESUME 2015JULIANA_BACCHUS_RESUME 2015
JULIANA_BACCHUS_RESUME 2015
 
Why Visual Content is Key for Oil & Gas Communications - Bill Roth [Energy Di...
Why Visual Content is Key for Oil & Gas Communications - Bill Roth [Energy Di...Why Visual Content is Key for Oil & Gas Communications - Bill Roth [Energy Di...
Why Visual Content is Key for Oil & Gas Communications - Bill Roth [Energy Di...
 
Brands & Publishers: A Symbiotic Relationship for the Digital Age - Stacy Mar...
Brands & Publishers: A Symbiotic Relationship for the Digital Age - Stacy Mar...Brands & Publishers: A Symbiotic Relationship for the Digital Age - Stacy Mar...
Brands & Publishers: A Symbiotic Relationship for the Digital Age - Stacy Mar...
 
Personal Branding: Career Management Strategies - Chris Westfall [Energy Digi...
Personal Branding: Career Management Strategies - Chris Westfall [Energy Digi...Personal Branding: Career Management Strategies - Chris Westfall [Energy Digi...
Personal Branding: Career Management Strategies - Chris Westfall [Energy Digi...
 

Similaire à Lambdas and Generics (long version) - Bordeaux/Toulouse JUG

Generics and Lambdas cocktail explained - Montreal JUG
Generics and Lambdas cocktail explained  - Montreal JUGGenerics and Lambdas cocktail explained  - Montreal JUG
Generics and Lambdas cocktail explained - Montreal JUGHenri Tremblay
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
computer notes - Data Structures - 32
computer notes - Data Structures - 32computer notes - Data Structures - 32
computer notes - Data Structures - 32ecomputernotes
 
Computer notes - Binary Search
Computer notes - Binary SearchComputer notes - Binary Search
Computer notes - Binary Searchecomputernotes
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda codePeter Lawrey
 
Using CUDA Within Mathematica
Using CUDA Within MathematicaUsing CUDA Within Mathematica
Using CUDA Within Mathematicakrasul
 
Using Cuda Within Mathematica
Using Cuda Within MathematicaUsing Cuda Within Mathematica
Using Cuda Within MathematicaShoaib Burq
 
Lambda expressions
Lambda expressionsLambda expressions
Lambda expressionsYuriy Seniuk
 
C++ Windows Forms L07 - Collections
C++ Windows Forms L07 - CollectionsC++ Windows Forms L07 - Collections
C++ Windows Forms L07 - CollectionsMohammad Shaker
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
Linq - an overview
Linq - an overviewLinq - an overview
Linq - an overviewneontapir
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Svetlin Nakov
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0Yaser Zhian
 
Computer notes - Hashing
Computer notes - HashingComputer notes - Hashing
Computer notes - Hashingecomputernotes
 
computer notes - Data Structures - 35
computer notes - Data Structures - 35computer notes - Data Structures - 35
computer notes - Data Structures - 35ecomputernotes
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 

Similaire à Lambdas and Generics (long version) - Bordeaux/Toulouse JUG (20)

Generics and Lambdas cocktail explained - Montreal JUG
Generics and Lambdas cocktail explained  - Montreal JUGGenerics and Lambdas cocktail explained  - Montreal JUG
Generics and Lambdas cocktail explained - Montreal JUG
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
computer notes - Data Structures - 32
computer notes - Data Structures - 32computer notes - Data Structures - 32
computer notes - Data Structures - 32
 
Computer notes - Binary Search
Computer notes - Binary SearchComputer notes - Binary Search
Computer notes - Binary Search
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
Using CUDA Within Mathematica
Using CUDA Within MathematicaUsing CUDA Within Mathematica
Using CUDA Within Mathematica
 
Using Cuda Within Mathematica
Using Cuda Within MathematicaUsing Cuda Within Mathematica
Using Cuda Within Mathematica
 
Lambda expressions
Lambda expressionsLambda expressions
Lambda expressions
 
C++ Windows Forms L07 - Collections
C++ Windows Forms L07 - CollectionsC++ Windows Forms L07 - Collections
C++ Windows Forms L07 - Collections
 
List,Stacks and Queues.pptx
List,Stacks and Queues.pptxList,Stacks and Queues.pptx
List,Stacks and Queues.pptx
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
Linq - an overview
Linq - an overviewLinq - an overview
Linq - an overview
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Computer notes - Hashing
Computer notes - HashingComputer notes - Hashing
Computer notes - Hashing
 
computer notes - Data Structures - 35
computer notes - Data Structures - 35computer notes - Data Structures - 35
computer notes - Data Structures - 35
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 

Plus de Henri Tremblay

DevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaDevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaHenri Tremblay
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?Henri Tremblay
 
Confoo 2018: Être pragmatique
Confoo 2018: Être pragmatiqueConfoo 2018: Être pragmatique
Confoo 2018: Être pragmatiqueHenri Tremblay
 
DevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingDevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingHenri Tremblay
 
Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028Henri Tremblay
 
Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017Henri Tremblay
 
Confoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de chargeConfoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de chargeHenri Tremblay
 
Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!Henri Tremblay
 
Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013Henri Tremblay
 
Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)Henri Tremblay
 
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...Henri Tremblay
 

Plus de Henri Tremblay (12)

DevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaDevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern Java
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
 
Confoo 2018: Être pragmatique
Confoo 2018: Être pragmatiqueConfoo 2018: Être pragmatique
Confoo 2018: Être pragmatique
 
DevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programmingDevNexus 2018: Learn Java 8, lambdas and functional programming
DevNexus 2018: Learn Java 8, lambdas and functional programming
 
Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028Do you know your mock? - Madras JUG 20171028
Do you know your mock? - Madras JUG 20171028
 
Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017Be Pragmatic - JavaOne 2017
Be Pragmatic - JavaOne 2017
 
Confoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de chargeConfoo 2016: Initiation aux tests de charge
Confoo 2016: Initiation aux tests de charge
 
Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!Réactif, parallèle, asynchrone. Pourquoi!
Réactif, parallèle, asynchrone. Pourquoi!
 
Perf university
Perf universityPerf university
Perf university
 
Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013Vivre en parallèle - Softshake 2013
Vivre en parallèle - Softshake 2013
 
Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)Performance perpétuelle (Devopsdays Paris 2013)
Performance perpétuelle (Devopsdays Paris 2013)
 
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the ...
 

Dernier

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 

Dernier (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Lambdas and Generics (long version) - Bordeaux/Toulouse JUG

  • 1. Les lambda arrivent! En attendant, êtes-vous sûr d'avoir compris les génériques? Henri Tremblay Architecte Senior OCTO Technology @henri_tremblay 27 au 29 mars 2013
  • 2. Les lambda arrivent! En attendant, êtes-vous sûr d'avoir compris les génériques? Henri Tremblay Architecte Senior OCTO Technology @henri_tremblay 27 au 29 mars 2013
  • 3. Henri Tremblay OCTO Technology Responsable R&D Performance Calcul parallèle Open Source EasyMock Objenesis
  • 10. Lambda = Fun with generics Stream<Tweet> stream = Tweet.TWEETS.stream(); Predicate<Tweet> lambda = t -> t.containsHashTag("#lambda"); Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector = Collectors.partitioningBy(lambda); return stream.collect(collector);
  • 11. Lambda = Fun with generics Stream<Tweet> stream = Tweet.TWEETS.stream(); Function<Tweet, Boolean> lambda = t -> t.containsHashTag("#lambda"); Collector<Tweet, Map<Boolean, List<Tweet>>> collector = Collectors.<Tweet, Boolean, List<Tweet>, Map<Boolean, List<Tweet>>> groupingBy(lambda, HashMap::new, ArrayList::new); return stream.collect(collector);
  • 12. What do I need to know? Why © OCTO 2011 12
  • 13. What do I need to know? Why Covariance © OCTO 2011 13
  • 14. What do I need to know? Why Covariance Capture © OCTO 2011 14
  • 15. What do I need to know? Why Covariance Capture Inference © OCTO 2011 15
  • 16. What do I need to know? Why Covariance Capture Inference Erasure © OCTO 2011 16
  • 17. What do I need to know? Why Covariance Capture Erasure © OCTO 2011 Inference Bridge 17
  • 19. Dreaded warnings Type safety: The expression of type List needs unchecked conversion to conform to List<String> Type safety: Unchecked cast from List<capture#1-of ?> to List<String> 19
  • 21. Why © OCTO 2011 21 27 au 29 mars 2013
  • 22. Rule #1 A code compiling without warning should never ever cause a ClassCastException 22
  • 24. Arrays Arrays are covariant: Number n = Integer.MAX_VALUE; Number[] list = new Integer[0]; Generics are not: List<Number> l = new ArrayList<Integer>(); // Illegal 24
  • 25. Why not? List<Integer> li = new ArrayList<Integer>(); List<Number> ln = li; // illegal ln.add(new Float(3.1415)); int i = li.get(0); // ClassCastException Would work if covariant And allow to break rule #1 25
  • 26. Why for array? Integer[] list = // ... foo(list); public void foo(Object[] o) { // ... }
  • 27. Arrays and generics don’t mix well Can’t have an array of generics List<String>[] lsa = new List<String>[10];// illegal 27
  • 28. Because If it was allowed List<String>[] lsa = new List<String>[10]; // illegal Object[] oa = lsa; // OK (covariant) oa[0] = new ArrayList<Integer>(); // OK String s = lsa[0].get(0); // bad 28
  • 29. Exception List<?>[] l = new ArrayList<?>[3]; 29
  • 30. Capture 30 27 au 29 mars 2013
  • 31. Capture usually is Type List<?> bar(); <T> IExpectationSetters<T> expect(T value); void andReturn(T value); // Method of IExpectationSetters expect(bar()).andReturn(new ArrayList<String>()); And you get The method andReturn(List<capture#6-of ?>) in the type IExpectationSetters<List<capture#6-of ?>> is not applicable for the arguments (ArrayList<String>) 31
  • 32. Detail List<?> bar(); <T> IExpectationSetters<T> expect(T value); void andReturn(T value); expect(bar()).andReturn(new ArrayList<String>()); List<Capture#6> bar = bar(); IExpectationSetters<List<Capture#6>> es = expect(bar()); es.andReturn(List<Capture#6> value); 32
  • 33. Only solution We need to cast expect((List<String>) bar()).andReturn(new Tell to expect we want a ArrayList<String>()); List<String> But still a warning Type safety: Unchecked cast from List<capture#6-of ?> to List<String> Framework coder tip: Try to never return a wildcard unless necessary 33
  • 35. Diamonds are a programmer best friend List<String> l = new ArrayList<>();
  • 36. How the compiler tells the type Determine the return value type The parameter <T> T anyObject(T clazz) 36
  • 37. How the compiler tells the type The assigned variable Determine the return type MyType var = <T> T anyObject() 37
  • 38. But watch out with overloading public void foo(String s) public void foo(Object o) foo(anyObject()); Can’t guess the type 38
  • 39. Trick #1 Determine the return value type Artificially give the type with a dedicated parameter <T> T anyObject(Class<T> clazz) 39
  • 40. But how to pass a generic? public void foo(String s) public void foo(Object o) foo(anyObject(List<String>.class)); Illegal 40
  • 41. Some solutions This would work foo((String) anyObject()); foo((List<String>) anyObject()); // Warning But still doesn’t work for generics 41
  • 42. Trick #2 So the only solution is foo(EasyMock.<List<String>> anyObject()); … which sadly doesn’t support static imports foo(.<List<String>> anyObject()); // Illegal 42
  • 43. Trick #2 applied to Lambda Return type: Map<Boolean, List<Tweet>> return Tweet.TWEETS.stream() .collect( Collectors.<Tweet, Boolean, List<Tweet>, Map<Boolean, List<Tweet>>> groupingBy(t->t.containsHashTag("#lambda"), HashMap::new, ArrayList::new));
  • 44. Lambda = Inference return Tweet.TWEETS.stream() .collect(Collectors .partitioningBy( t->t.containsHashTag("#lambda"));
  • 45. How did he do it? List<Tweet> list = Tweet.TWEETS; Stream<Tweet> stream = list.stream(); R result = stream.collect(Collector<? super T, ?, R> collector); R result = stream.collect(Collector<? super Tweet, ?, R> collector); Collector<T, ?, Map<Boolean, List<T>>> collector = Collectors.partitioningBy(Predicate<? super T> predicate); Collector<Tweet, ?, Map<Boolean, List<Tweet>>> collector = Collectors.partitioningBy(Predicate<? super Tweet> predicate); Map<Boolean, List<Tweet>> result = stream.collect(Collector<? super Tweet, ?, Map<Boolean, List<Tweet>>> collector); Predicate<? super Tweet> lambda = (Tweet t) -> t.containsHashTag("#lambda");
  • 46. Trick #3: Lambda inference Object o = (Runnable) () -> { System.out.println("hi"); }; Collections.sort(strings, (String a, String b) -> a.compareTo(b));
  • 48. Erasure… public void foo() { List<String> l = new ArrayList<String>(); for (String s : l) { No type System.out.println(s); } public void foo() { } List l = new ArrayList(); for (String s : l) { System.out.println(s); Compilation } }
  • 49. … or not erasure public class A extends ArrayList<String> {} public static void main(final String[] args) { ParameterizedType type = (ParameterizedType) A.class.getGenericSuperclass(); System.out.println( type.getActualTypeArguments()[0]); }  prints class java.lang.String 49
  • 50. Type class java.lang.reflect.Type • • • • • GenericArrayType ParameterizedType TypeVariable WildcardType Implemented by Class New powers unleashed! java.lang.reflect.GenericDeclaration Implemented by Class, Method, Constructor 50
  • 51. Useful! class A {} abstract class BaseDao<T> { public T load(final long id) { // … } } class ADao extends BaseDao<A> {} © OCTO 2011 51
  • 52. Useful! @SuppressWarnings("unchecked") public T load(final long id) { ParameterizedType type = (ParameterizedType) getClass() .getGenericSuperclass(); ADao BaseDao<A> A Type actualType = type.getActualTypeArguments()[0]; return em.find((Class<T>) actualType, (Long) id); } Unsafe cast
  • 54. Everything seems normal… class A<T> { abstract void set(T value); } class B extends A<String> { String value; @Override void set(final String value) { this.value = value; } }
  • 55. But is not class B extends A { void set(String value) { this.value = value; } volatile void set(Object o){ set((String)o); } }
  • 56. Example Raw type warning Perfectly compiling A a = new B(); a.set(new Object()); But at runtime: java.lang.ClassCastException
  • 57. The actual problem being B.class.getDeclaredMethods() This Returns that volatile void set(java.lang.Object) void B.set(java.lang.String) And gives you no way to find out which method is bridged
  • 58. What about lambdas? public class A { public static void main(String[] args) { Method[] methods = A.class.getDeclaredMethods(); Arrays.stream(methods).forEach(m -> System.out.println(m + " " + m.isBridge() + " " + m.isSynthetic())); } } Prints this public static void A.main(java.lang.String[]) false false private static void A.lambda$0(java.lang.reflect.Method) false true
  • 59. Conclusion Who has learned something today? © OCTO 2011 59
  • 60. Useful links Nice lambda tutorial (in French): http://lambda.ninjackaton.ninja-squad.com/ Description of inference types on lambda: http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html Everything on generics: http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html