SlideShare a Scribd company logo
1 of 61
27 au 29 mars 2013
Les lambda sont là!
Mais êtes-vous sûr d'avoir
compris les génériques?
Henri Tremblay
Architecte Senior
Pages Jaunes
@henri_tremblay
Amateur de
Stratégie TI
Performance
Productivité
Bons vins, bières, whiskies…
Fait de l’Open Source
Henri Tremblay
Aime être utile
March 18 2014
Java 7 End of Life
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?
9© OCTO 2011
Why
What do I need to know?
10© OCTO 2011
Why
Covariance
What do I need to know?
11© OCTO 2011
Why
Covariance
Capture
What do I need to know?
12© OCTO 2011
Why
Covariance
Capture
Inference
What do I need to know?
13© OCTO 2011
Why
Covariance
Capture
Inference
Erasure
What do I need to know?
14© OCTO 2011
Why Covariance
Capture Inference
Erasure Bridge
Faire compiler
15
Dreaded warnings
16
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>
Ostrich defense
@SuppressWarnings("unchecked")
17
27 au 29 mars 2013
Why
18© OCTO 2011
Rule #1
A code compiling
without warning should
never ever cause a
ClassCastException
19
27 au 29 mars 2013
Covariance
20
Arrays
Arrays are covariant:
Number n = Integer.MAX_VALUE;
Number[] list = new Integer[0];
Generics are not:
List<Number> l =
new ArrayList<Integer>(); // Illegal
21
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
22
Would work if covariant And allow to break rule #1
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
24
Exception
List<?>[] l = new ArrayList<?>[3];
25
Because
If it was allowed
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK (covariant)
oa[0] = new ArrayList<Integer>(); // OK
oa[0].add(42);
String s = lsa[0].get(0); // bad
26
27 au 29 mars 2013
Capture
27
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>)
28
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);
29
Only solution
We need to cast
expect((List<String>) bar()).andReturn(new
ArrayList<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
30
Tell to expect we want a
List<String>
Inference
31
Diamonds are a programmer best friend
List<String> l = new ArrayList<>();
How the compiler tells the type
<T> T anyObject(T clazz)
33
The parameterDetermine
the return
value type
How the compiler tells the type
MyType var = <T> T anyObject()
34
Determine the
return type
The assigned
variable
But watch out with overloading
public void foo(String s)
public void foo(Object o)
foo(anyObject());
35
Can’t
guess the
type
Trick #1
<T> T anyObject(Class<T> clazz)
36
Artificially give the type with a
dedicated parameter
Determine the return
value type
But how to pass a generic?
public void foo(String s)
public void foo(Object o)
foo(anyObject(List<String>.class));
37
Illegal
Some solutions
foo((String) anyObject());
foo((List<String>) anyObject()); // Warning
38
This would work
But still doesn’t work for
generics
Trick #2
So the only solution is
foo(EasyMock.<List<String>> anyObject());
… which sadly doesn’t support static imports
foo(.<List<String>> anyObject()); // Illegal
39
Trick #2 applied to Lambda
return Tweet.TWEETS.stream()
.collect( Collectors.<Tweet, Boolean,
List<Tweet>, Map<Boolean, List<Tweet>>>
groupingBy(t->t.containsHashTag("#lambda"),
HashMap::new, ArrayList::new));
Return type: Map<Boolean, List<Tweet>>
Lambda = Inference
return Tweet.TWEETS.stream()
.collect(Collectors
.partitioningBy(
t->t.containsHashTag("#lambda"));
How did it do it?
Tweet.TWEETS.stream()
List<Tweet> list = Tweet.TWEETS;
Stream<Tweet> stream = list.stream();
How did it do it?
Stream<Tweet> stream = list.stream();
R result = stream.collect(Collector<? super T, ?, R> collector);
R result = stream.collect(Collector<? super Tweet, ?, R> collector);
How did it do it?
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);
How did it do it?
Predicate<? super Tweet> lambda = t -> t.containsHashTag("#lambda");
We now know that
So the best t can be is a Tweet
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) {
System.out.println(s);
}
}
No type
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
java.lang.reflect.GenericDeclaration
Implemented by Class, Method, Constructor
50
New powers unleashed!
Useful!
class A {}
abstract class BaseDao<T> {
public T load(final long id) {
// …
}
}
class ADao extends BaseDao<A> {}
51© OCTO 2011
Useful!
@SuppressWarnings("unchecked")
public T load(final long id) {
ParameterizedType type =
(ParameterizedType) getClass()
.getGenericSuperclass();
Type actualType = type.getActualTypeArguments()[0];
return em.find((Class<T>) actualType, (Long) id);
}
ADao
A
BaseDao<A>
Unsafe cast
Bridge
53© OCTO 2011
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
A a = new B();
a.set(new Object());
But at runtime:
java.lang.ClassCastException
Raw type warning Perfectly compiling
The actual problem being
B.class.getDeclaredMethods()
volatile void set(java.lang.Object)
void B.set(java.lang.String)
This
Returns that
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?
59© OCTO 2011
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
Hopefully everything on lambdas
http://www.lambdafaq.org/
Conclusion
Questions?
61© OCTO 2011
http://perfug.github.io/
http://brownbaglunch.fr
+Henri Tremblay
@henri_tremblay
henri@tremblay.pro

More Related Content

What's hot

Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayKevlin Henney
 
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
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?UFPA
 

What's hot (20)

Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
 
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
 
ALF 5 - Parser Top-Down
ALF 5 - Parser Top-DownALF 5 - Parser Top-Down
ALF 5 - Parser Top-Down
 
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...
 
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
 
Lec2
Lec2Lec2
Lec2
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
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
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?
 

Viewers also liked

Aula de yoga preço
Aula de yoga preçoAula de yoga preço
Aula de yoga preçoAruna Yoga
 
Future on power electronics for wind turbine systems
Future on power electronics for wind turbine systemsFuture on power electronics for wind turbine systems
Future on power electronics for wind turbine systemsKashish Srivastava
 
How to Build Hardware Lean
How to Build Hardware LeanHow to Build Hardware Lean
How to Build Hardware LeanDiUS
 
Top Ten Reasons Libraries Are Still Important
Top Ten Reasons Libraries Are Still ImportantTop Ten Reasons Libraries Are Still Important
Top Ten Reasons Libraries Are Still Importantbradspry
 
History of Public Libraries
History of Public LibrariesHistory of Public Libraries
History of Public Librariesannaha
 
Ahmed Khamis Resume_2016
Ahmed Khamis Resume_2016Ahmed Khamis Resume_2016
Ahmed Khamis Resume_2016Ahmed Mounir
 
Exploring food for babies beyond 6 months old
Exploring food for babies beyond 6 months oldExploring food for babies beyond 6 months old
Exploring food for babies beyond 6 months oldJessWongHuiJuan1
 

Viewers also liked (8)

Aula de yoga preço
Aula de yoga preçoAula de yoga preço
Aula de yoga preço
 
Gds amadeus
Gds amadeusGds amadeus
Gds amadeus
 
Future on power electronics for wind turbine systems
Future on power electronics for wind turbine systemsFuture on power electronics for wind turbine systems
Future on power electronics for wind turbine systems
 
How to Build Hardware Lean
How to Build Hardware LeanHow to Build Hardware Lean
How to Build Hardware Lean
 
Top Ten Reasons Libraries Are Still Important
Top Ten Reasons Libraries Are Still ImportantTop Ten Reasons Libraries Are Still Important
Top Ten Reasons Libraries Are Still Important
 
History of Public Libraries
History of Public LibrariesHistory of Public Libraries
History of Public Libraries
 
Ahmed Khamis Resume_2016
Ahmed Khamis Resume_2016Ahmed Khamis Resume_2016
Ahmed Khamis Resume_2016
 
Exploring food for babies beyond 6 months old
Exploring food for babies beyond 6 months oldExploring food for babies beyond 6 months old
Exploring food for babies beyond 6 months old
 

Similar to Generics and Lambdas cocktail explained - Montreal JUG

Lambdas and Generics (long version) - Bordeaux/Toulouse JUG
Lambdas and Generics (long version) - Bordeaux/Toulouse JUGLambdas and Generics (long version) - Bordeaux/Toulouse JUG
Lambdas and Generics (long version) - Bordeaux/Toulouse JUGHenri Tremblay
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda codePeter Lawrey
 
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
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++Neeru Mittal
 
Applying Generics
Applying GenericsApplying Generics
Applying GenericsBharat17485
 
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
 
Linq - an overview
Linq - an overviewLinq - an overview
Linq - an overviewneontapir
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
CS253: Priority queues (2019)
CS253: Priority queues (2019)CS253: Priority queues (2019)
CS253: Priority queues (2019)Jinho Choi
 
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
 
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdfaristogifts99
 
Computer notes - Binary Search
Computer notes - Binary SearchComputer notes - Binary Search
Computer notes - Binary Searchecomputernotes
 
computer notes - Data Structures - 32
computer notes - Data Structures - 32computer notes - Data Structures - 32
computer notes - Data Structures - 32ecomputernotes
 
Lambda expressions
Lambda expressionsLambda expressions
Lambda expressionsYuriy Seniuk
 

Similar to Generics and Lambdas cocktail explained - Montreal JUG (20)

Lambdas and Generics (long version) - Bordeaux/Toulouse JUG
Lambdas and Generics (long version) - Bordeaux/Toulouse JUGLambdas and Generics (long version) - Bordeaux/Toulouse JUG
Lambdas and Generics (long version) - Bordeaux/Toulouse JUG
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
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.
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Applying Generics
Applying GenericsApplying Generics
Applying Generics
 
Computer notes - Hashing
Computer notes - HashingComputer notes - Hashing
Computer notes - Hashing
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
computer notes - Data Structures - 35
computer notes - Data Structures - 35computer notes - Data Structures - 35
computer notes - Data Structures - 35
 
Linq - an overview
Linq - an overviewLinq - an overview
Linq - an overview
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
CS253: Priority queues (2019)
CS253: Priority queues (2019)CS253: Priority queues (2019)
CS253: Priority queues (2019)
 
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
 
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
Computer notes - Binary Search
Computer notes - Binary SearchComputer notes - Binary Search
Computer notes - Binary Search
 
U3.pptx
U3.pptxU3.pptx
U3.pptx
 
unit 3 ppt.pptx
unit 3 ppt.pptxunit 3 ppt.pptx
unit 3 ppt.pptx
 
computer notes - Data Structures - 32
computer notes - Data Structures - 32computer notes - Data Structures - 32
computer notes - Data Structures - 32
 
Lambda expressions
Lambda expressionsLambda expressions
Lambda expressions
 

More from 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
 
Microbenchmarking with JMH
Microbenchmarking with JMHMicrobenchmarking with JMH
Microbenchmarking with JMHHenri 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
 

More from Henri Tremblay (13)

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
 
Microbenchmarking with JMH
Microbenchmarking with JMHMicrobenchmarking with JMH
Microbenchmarking with JMH
 
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 ...
 

Recently uploaded

A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 

Generics and Lambdas cocktail explained - Montreal JUG

  • 1. 27 au 29 mars 2013 Les lambda sont là! Mais êtes-vous sûr d'avoir compris les génériques? Henri Tremblay Architecte Senior Pages Jaunes @henri_tremblay
  • 2. Amateur de Stratégie TI Performance Productivité Bons vins, bières, whiskies… Fait de l’Open Source Henri Tremblay Aime être utile
  • 4. Java 7 End of Life
  • 7. 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);
  • 8. 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);
  • 9. What do I need to know? 9© OCTO 2011 Why
  • 10. What do I need to know? 10© OCTO 2011 Why Covariance
  • 11. What do I need to know? 11© OCTO 2011 Why Covariance Capture
  • 12. What do I need to know? 12© OCTO 2011 Why Covariance Capture Inference
  • 13. What do I need to know? 13© OCTO 2011 Why Covariance Capture Inference Erasure
  • 14. What do I need to know? 14© OCTO 2011 Why Covariance Capture Inference Erasure Bridge
  • 16. Dreaded warnings 16 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>
  • 18. 27 au 29 mars 2013 Why 18© OCTO 2011
  • 19. Rule #1 A code compiling without warning should never ever cause a ClassCastException 19
  • 20. 27 au 29 mars 2013 Covariance 20
  • 21. Arrays Arrays are covariant: Number n = Integer.MAX_VALUE; Number[] list = new Integer[0]; Generics are not: List<Number> l = new ArrayList<Integer>(); // Illegal 21
  • 22. 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 22 Would work if covariant And allow to break rule #1
  • 23. Why for array? Integer[] list = // ... foo(list); public void foo(Object[] o) { // ... }
  • 24. Arrays and generics don’t mix well Can’t have an array of generics List<String>[] lsa = new List<String>[10];// illegal 24
  • 25. Exception List<?>[] l = new ArrayList<?>[3]; 25
  • 26. Because If it was allowed List<String>[] lsa = new List<String>[10]; // illegal Object[] oa = lsa; // OK (covariant) oa[0] = new ArrayList<Integer>(); // OK oa[0].add(42); String s = lsa[0].get(0); // bad 26
  • 27. 27 au 29 mars 2013 Capture 27
  • 28. 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>) 28
  • 29. 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); 29
  • 30. Only solution We need to cast expect((List<String>) bar()).andReturn(new ArrayList<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 30 Tell to expect we want a List<String>
  • 32. Diamonds are a programmer best friend List<String> l = new ArrayList<>();
  • 33. How the compiler tells the type <T> T anyObject(T clazz) 33 The parameterDetermine the return value type
  • 34. How the compiler tells the type MyType var = <T> T anyObject() 34 Determine the return type The assigned variable
  • 35. But watch out with overloading public void foo(String s) public void foo(Object o) foo(anyObject()); 35 Can’t guess the type
  • 36. Trick #1 <T> T anyObject(Class<T> clazz) 36 Artificially give the type with a dedicated parameter Determine the return value type
  • 37. But how to pass a generic? public void foo(String s) public void foo(Object o) foo(anyObject(List<String>.class)); 37 Illegal
  • 38. Some solutions foo((String) anyObject()); foo((List<String>) anyObject()); // Warning 38 This would work But still doesn’t work for generics
  • 39. Trick #2 So the only solution is foo(EasyMock.<List<String>> anyObject()); … which sadly doesn’t support static imports foo(.<List<String>> anyObject()); // Illegal 39
  • 40. Trick #2 applied to Lambda return Tweet.TWEETS.stream() .collect( Collectors.<Tweet, Boolean, List<Tweet>, Map<Boolean, List<Tweet>>> groupingBy(t->t.containsHashTag("#lambda"), HashMap::new, ArrayList::new)); Return type: Map<Boolean, List<Tweet>>
  • 41. Lambda = Inference return Tweet.TWEETS.stream() .collect(Collectors .partitioningBy( t->t.containsHashTag("#lambda"));
  • 42. How did it do it? Tweet.TWEETS.stream() List<Tweet> list = Tweet.TWEETS; Stream<Tweet> stream = list.stream();
  • 43. How did it do it? Stream<Tweet> stream = list.stream(); R result = stream.collect(Collector<? super T, ?, R> collector); R result = stream.collect(Collector<? super Tweet, ?, R> collector);
  • 44. How did it do it? 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);
  • 45. How did it do it? Predicate<? super Tweet> lambda = t -> t.containsHashTag("#lambda"); We now know that So the best t can be is a Tweet 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) { System.out.println(s); } } No type 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 java.lang.reflect.GenericDeclaration Implemented by Class, Method, Constructor 50 New powers unleashed!
  • 51. Useful! class A {} abstract class BaseDao<T> { public T load(final long id) { // … } } class ADao extends BaseDao<A> {} 51© OCTO 2011
  • 52. Useful! @SuppressWarnings("unchecked") public T load(final long id) { ParameterizedType type = (ParameterizedType) getClass() .getGenericSuperclass(); Type actualType = type.getActualTypeArguments()[0]; return em.find((Class<T>) actualType, (Long) id); } ADao A BaseDao<A> 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 A a = new B(); a.set(new Object()); But at runtime: java.lang.ClassCastException Raw type warning Perfectly compiling
  • 57. The actual problem being B.class.getDeclaredMethods() volatile void set(java.lang.Object) void B.set(java.lang.String) This Returns that 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? 59© OCTO 2011
  • 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 Hopefully everything on lambdas http://www.lambdafaq.org/

Editor's Notes

  1. Hors le fait que ça nous donne des magnifiques oneliners, on y croise une quantité particulièrement épique de génériques
  2. Malheureusement, quand on le sépare en petits morceaux, nous voyons apparaître des tonnes de génériques. La bonne nouvelle, c’est que ça s’est amélioré. La dernière fois que j’ai donné cette conférence, ça ressemblait plutôt à ça
  3. L’API était nettement plus complexe et il restait certains problèmes d’inférence L’inférence, c’est le fait de deviner le type. Comme dans le Collectors ici. On en avait un peu depuis l’arrivé des génériques et il y en a maintenant beaucoup plus avec les lambda
  4. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  5. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  6. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  7. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  8. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  9. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  10. Emplit de désespoir vous ne savez pas trop comment vous en débarasser parce que toutes vos tentatives ne compilent pas.
  11. Emplit de désespoir vous ne savez pas trop comment vous en débarasser parce que toutes vos tentatives ne compilent pas.
  12. Et vous terminez, pas trop fier de vous et pas trop sûr d’avoir compris le problème avec un aborable SuppressWarning. Cette session a pour but de vous faire comprendre 1- Pourquoi vous avez ces erreurs 2- Pourquoi c’est fait comme ça 3- Comment c’est implémenté
  13. Par exemple, les arrays
  14. C’est cette règle qui a forcé plusieurs décisions de design et qui a par conséquent rendu notre ami le @SuppressWarning si fréquent. On en vient à ce demander comment ils auraient fait si les annotations n’étaient pas apparu au même moment.
  15. Par exemple, les arrays
  16. Les arrays sont covariants. Si on peut assigner un object d’un type donné à un autre type, alors on peut assigner un array d’objet à un array de l’autre type Par contre pour les génériques on ne peut pas. Il est illégal de faire la ligne du bas. Car, un code qui compile sans warning ne doit jamais jamais causé un ClassCastException
  17. Un exemple que vous avez sûrement déjà vu pour expliquer pourquoi c’est interdit. Comme vous voyez, si la covariance était permisse nous briserions la règle #1 Et pour un array
  18. Parce que pour un tableau, on a envie que ça ça passe
  19. On ne peut pas faire de tableau de génériques et c’est bien dommage. Une seule exception, un tableau de wildcard. Le wildcard étant un type quelconque, nous n’avons pas de soucis. Dans tous les autres cas c’est interdit pour la raison suivante
  20. On ne peut pas faire de tableau de génériques et c’est bien dommage. Une seule exception, un tableau de wildcard. Le wildcard étant un type quelconque, nous n’avons pas de soucis. Dans tous les autres cas c’est interdit pour la raison suivante
  21. Nous avons le cas suivant. Grâce une asticieuse utilisation de la covariance des arrays, si les arrays génériques étaient permis, nous briserions la règle numéro 1. En résumé, si les designers des génériques avaient laissé tomber la règle pour ce cas et laisser le bénéfice du doute au développeur, nous aurions échappé à plusieurs complexité. Je vous laisse juge de leur décision.
  22. Par exemple, les arrays
  23. Une méthode retourne un type en wildcard Pour garder la cohérence, le compilateur va fixer le type et l’appeler capture#6 pour s’assurer de la cohérence du type donné à T Pour les développeurs de framework, ne jamais retourner de wildcard si possible
  24. Une méthode retourne un type en wildcard Pour garder la cohérence, le compilateur va fixer le type et l’appeler capture#6 pour s’assurer de la cohérence du type donné à T Pour les développeurs de framework, ne jamais retourner de wildcard si possible
  25. Warning mandatory pour ne pas enfreindre la règle #1
  26. Par exemple, les arrays
  27. Lorsqu’il y a un paramètre, le compilateur prend le type du paramètre pour déterminer le type de retour. Cette pour cette raison que le syntaxe que vous voyez est apparu en Java 5. Le paramètre ne sert à rien sauf à fixer le type. Mais ça vous les savez sûrement déjà.
  28. Ensuite s’il n’y a pas de paramètre, le compilateur déduit le type à partir de la variable à laquelle elle est assignée. Mais ça ne marche pas à tous les coups.
  29. Dans les cas d’overloading par exemple. Impossible de deviner quelle méthode doit être appelé
  30. Un truc classique est d’ajouter un paramètre juste pour la bonne cause. C’est un contournement classique.
  31. Dans les cas d’overloading par exemple. Impossible de deviner quelle méthode doit être appelé
  32. Pour les lambda, il est très fort probable d’en avoir besoin. Vous avez ici l’exemple du début où je l’utilisais. Fort heureusement, ce n’est pas nécessaire dans la nouvelle API. Par contre, j’ai un peu de difficulté à vous promettre que ce sera toujours le cas. On touche du bois
  33. Par exemple, les arrays
  34. Everybody knows what is erasure? List<String> and ArrayList<String> got erasure The variable in the loop kept is type Boring, nous on va parler des cas où il n’y a pas d’erasure.
  35. Oh dear, no erasure On récupère la classe parent qui s’avère être générique et implémente donc l’interface ParameterizedType.
  36. Il y a eu un ajout de plusieurs interfaces. Elles sont passées presque complètement inaperçu mais peuvent être utile. Par exemple, l’exemple précédent peut servir à faire ça
  37. Par polymorphisme, le getClass() retourne ADao. Donc la superclass est BaseDao, et le type du paramètre générique est A. And yes, the dumb part if the SuppressWarnings. It comes come the (Class<T>) cast. Since the compiler can’t be sure that actualType is a Class, we get the warning. On ne peut pas s’en débarasser.
  38. Par exemple, les arrays
  39. Vous avez une classe générique étendue par un autre qui fixe le type à String. Rien de plus classique.
  40. Magie, à la décompilation, une nouvelle méthode est apparue. C’est le bridge. Elle ne sert à rien sauf à l’assurer c’est bien une String qui est passé en paramètre. Le volatile c’est parce que la modificateur de champs et de méthodes ont des codes communs. Donc en fait, le décompilateur (jad) a un petit bogue. Attention, Java Decompiler ne vous montrera pas le bridge, il le fait disparaitre. On ne le voit qu’avec Jad qui est moins futé.
  41. La règle #1 n’est pas enfreinte car nous avons un warning. Par contre, Java ajoute dans ce cas particulier une sur-protection. Impossible de s’en prémunir à la compilation. Tout est valide. Il fallait donc combler la faille pour empêcher un Object d’être assigné à une String et amener le chaos et l’anarchie dans la JVM. D’où, le bridge.
  42. Vous avez deux méthodes. L’une déléguant directement à l’autre. Si vous avez un framework faisant des proxies dynamiques ou de l’AOP, vous vous retrouvez avec deux méthodes instrumentées. Et c’est assez rare que c’est ce que vous aviez prévus. Résultat, plus rien ne marche. Par exemple, Spring qui utilise beaucoup de proxies, a dû implémenter une class nommée BridgeMethodResolver qui permet de trouver la méthode concrête appelée par le bridge. Et malheureusement, le JDK n’a pas prévu le coup donc il faut la déduire. C’est ce que j’avais de plus compliqué à vous montrer aujourd’hui. Passons donc à la conclusion.
  43. J’ai pas mal pataugé sur ces sujets car ils sont assez peu documentés. C’est pas simple mais on finit par s’y retrouver. La question qui me taraude maintenant c’est “Est-ce que vous connaissiez tout ça?” Pour m’assurez que je ne raconte pas que des banalités. Est-ce que chaque personne pourrait lever la main et me dire si vous avez appris au moins une chose aujourd’hui?
  44. Maurice Naftalin
  45. Oh dear, no erasure