SlideShare uma empresa Scribd logo
1 de 35
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       Open Source
    Responsable R&D      EasyMock
    Performance          Objenesis
    Calcul parallèle
September 2013
September 2013
September 2013
What do I need to know?

              Why




© OCTO 2011                 7
What do I need to know?

              Why
                    Covariance




© OCTO 2011                      8
What do I need to know?

              Why
                        Covariance

              Capture



© OCTO 2011                          9
What do I need to know?

              Why
                        Covariance

              Capture

                               Erasure

© OCTO 2011                              10
What do I need to know?

              Why
                             Covariance

              Capture

                                 Erasure
                    Bridge
© OCTO 2011                                11
What do I need to know?

              Why
                             Covariance

              Capture

                                 Erasure
                    Bridge
© OCTO 2011                                12
Lambda


 return Tweet.TWEETS.stream()
   .collect(Collectors
   .groupingBy(t->t.containsHashTag("#lambda"),
     HashMap::new, ArrayList::new));
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);
Lambda = Inférence


 return Tweet.TWEETS.stream()
   .collect( Collectors
   .groupingBy(t->t.containsHashTag("#lambda"),
     HashMap::new, ArrayList::new));
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>

© OCTO 2011                                                           16
Ostrich defense
              @SuppressWarnings("unchecked")




© OCTO 2011                              17
Why



© OCTO 2011         18
Rule #1


                  A code compiling
               without warning should
                never ever cause a
              ClassCastException
© OCTO 2011                         19
Capture



© OCTO 2011             20
Capture usually is
       Type
       List<?> bar();
       <T> IExpectationSetters<T> expect(T value);
       void andReturn(T value); // Method of IExpectationSetters
                                                            Returns a capture#6
       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>)

© OCTO 2011                                                                        21
Only solution
       We need to cast
       expect((List<String>) bar()).andReturn(new
        ArrayList<String>());       Tell to expect we want a
                                                          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
© OCTO 2011                                                              22
How the compiler tells the type
              Determine     The parameter
              the return
              value type




              <T> T anyObject(T clazz)


© OCTO 2011                                 23
How the compiler tells the type
                 The assigned   Determine the
                 variable       return type




              MyType var = <T> T anyObject()


© OCTO 2011                                     24
But watch out with overloading

       public void foo(String s)
       public void foo(Object o)

       foo(anyObject());
                           Can’t
                           guess the
                           type

© OCTO 2011                            25
Trick #1
              Determine the return   Artificially give the type with a
              value type             dedicated parameter




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


© OCTO 2011                                                26
But how to pass a generic?
       public void foo(String s)
       public void foo(Object o)

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

                                   Examples:
                      Illegal      ToXXXFunction
© OCTO 2011                              27
Example

    • Collectors.mapping params
        •     Function, Collector
        •     ToIntFunction, Collector.OfInt
        •     ToLongFunction , Collector.OfLong
        •     ToDoubleFunction, , Collector.OfDouble



© OCTO 2011                                 28
Some solutions

                          This would work


       foo((String) anyObject());

       foo((List<String>) anyObject()); // Warning

                                     But still doesn’t work for
                                     generics
© OCTO 2011                                          29
Trick #2

       So the only solution is

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

       … which sadly doesn’t support static imports

       foo(.<List<String>> anyObject()); // Illegal


© OCTO 2011                                   30
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));
Trick #3: Lambda inference


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

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

              Who has learned
              something today?


© OCTO 2011                      33
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-4.html


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


               Questions?



© OCTO 2011                 35

Mais conteúdo relacionado

Mais procurados

How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITEgor Bogatov
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Romain Francois
 
Building Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual MachinesBuilding Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual MachinesGuido Chari
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeDmitri Nesteruk
 
What\'s New in C# 4.0
What\'s New in C# 4.0What\'s New in C# 4.0
What\'s New in C# 4.0Eyal Vardi
 
Functional Reactive Programming by Gerold Meisinger
Functional Reactive Programming by Gerold MeisingerFunctional Reactive Programming by Gerold Meisinger
Functional Reactive Programming by Gerold MeisingerGeroldMeisinger
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️Egor Bogatov
 
SOA in the cloud with FraSCAti, OW2con11, Nov 24-25, Paris
SOA in the cloud with FraSCAti, OW2con11, Nov 24-25, ParisSOA in the cloud with FraSCAti, OW2con11, Nov 24-25, Paris
SOA in the cloud with FraSCAti, OW2con11, Nov 24-25, ParisOW2
 
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)Igalia
 
35787646 system-software-lab-manual
35787646 system-software-lab-manual35787646 system-software-lab-manual
35787646 system-software-lab-manualNaveen Kumar
 
Parametrized Model Checking of Fault Tolerant Distributed Algorithms by Abstr...
Parametrized Model Checking of Fault Tolerant Distributed Algorithms by Abstr...Parametrized Model Checking of Fault Tolerant Distributed Algorithms by Abstr...
Parametrized Model Checking of Fault Tolerant Distributed Algorithms by Abstr...Iosif Itkin
 

Mais procurados (20)

How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
Building Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual MachinesBuilding Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual Machines
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 
What\'s New in C# 4.0
What\'s New in C# 4.0What\'s New in C# 4.0
What\'s New in C# 4.0
 
Functional Reactive Programming by Gerold Meisinger
Functional Reactive Programming by Gerold MeisingerFunctional Reactive Programming by Gerold Meisinger
Functional Reactive Programming by Gerold Meisinger
 
Exploiting vectorization with ISPC
Exploiting vectorization with ISPCExploiting vectorization with ISPC
Exploiting vectorization with ISPC
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
 
Roslyn: el futuro de C#
Roslyn: el futuro de C#Roslyn: el futuro de C#
Roslyn: el futuro de C#
 
L8
L8L8
L8
 
SOA in the cloud with FraSCAti, OW2con11, Nov 24-25, Paris
SOA in the cloud with FraSCAti, OW2con11, Nov 24-25, ParisSOA in the cloud with FraSCAti, OW2con11, Nov 24-25, Paris
SOA in the cloud with FraSCAti, OW2con11, Nov 24-25, Paris
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
 
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)
 
Lecture05
Lecture05Lecture05
Lecture05
 
Codejunk Ignitesd
Codejunk IgnitesdCodejunk Ignitesd
Codejunk Ignitesd
 
35787646 system-software-lab-manual
35787646 system-software-lab-manual35787646 system-software-lab-manual
35787646 system-software-lab-manual
 
C# looping basic
C# looping basicC# looping basic
C# looping basic
 
Parametrized Model Checking of Fault Tolerant Distributed Algorithms by Abstr...
Parametrized Model Checking of Fault Tolerant Distributed Algorithms by Abstr...Parametrized Model Checking of Fault Tolerant Distributed Algorithms by Abstr...
Parametrized Model Checking of Fault Tolerant Distributed Algorithms by Abstr...
 
Permute
PermutePermute
Permute
 
Stack
StackStack
Stack
 

Destaque

Greeley West High School - Teacher Work Sample
Greeley West High School - Teacher Work SampleGreeley West High School - Teacher Work Sample
Greeley West High School - Teacher Work SampleChris Colson
 
Pc-World "Monta la pc de tus sueños"
Pc-World "Monta la pc de tus sueños"Pc-World "Monta la pc de tus sueños"
Pc-World "Monta la pc de tus sueños"Brayan Castro Romero
 
Magento 2 Theme Localization
Magento 2 Theme LocalizationMagento 2 Theme Localization
Magento 2 Theme LocalizationSergii Shymko
 
SILABO DE DEONTOLOGIA JURIDICA
SILABO DE DEONTOLOGIA JURIDICASILABO DE DEONTOLOGIA JURIDICA
SILABO DE DEONTOLOGIA JURIDICAGabrielaCapelo
 
Aprende a elegir tu talla y medir correctamente ARDYSS
Aprende a elegir tu talla y medir correctamente ARDYSSAprende a elegir tu talla y medir correctamente ARDYSS
Aprende a elegir tu talla y medir correctamente ARDYSSArdyss Colombia
 
E cap 1- projeto-conceitos, atribuições e responsabilidade
E cap 1- projeto-conceitos, atribuições e responsabilidadeE cap 1- projeto-conceitos, atribuições e responsabilidade
E cap 1- projeto-conceitos, atribuições e responsabilidadeAndré Felipe
 
E cap 8- dimensionamento de eletrodutos
E cap 8- dimensionamento de eletrodutosE cap 8- dimensionamento de eletrodutos
E cap 8- dimensionamento de eletrodutosAndré Felipe
 
Shampoo y acondicionador
Shampoo y acondicionadorShampoo y acondicionador
Shampoo y acondicionadorArdyss Colombia
 
El mundo Globalizado
El mundo GlobalizadoEl mundo Globalizado
El mundo Globalizadohermesquezada
 
Ensayo sobre derechos humanos y garantías constitucionales
Ensayo sobre derechos humanos y garantías constitucionalesEnsayo sobre derechos humanos y garantías constitucionales
Ensayo sobre derechos humanos y garantías constitucionalessolsideth
 

Destaque (16)

Lei Menino Bernardo
Lei Menino BernardoLei Menino Bernardo
Lei Menino Bernardo
 
Greeley West High School - Teacher Work Sample
Greeley West High School - Teacher Work SampleGreeley West High School - Teacher Work Sample
Greeley West High School - Teacher Work Sample
 
Pc-World "Monta la pc de tus sueños"
Pc-World "Monta la pc de tus sueños"Pc-World "Monta la pc de tus sueños"
Pc-World "Monta la pc de tus sueños"
 
Teoria del liderazgo
Teoria del liderazgoTeoria del liderazgo
Teoria del liderazgo
 
Magento 2 Theme Localization
Magento 2 Theme LocalizationMagento 2 Theme Localization
Magento 2 Theme Localization
 
La situación actual de aplicación práctica en las
La situación actual de aplicación práctica en lasLa situación actual de aplicación práctica en las
La situación actual de aplicación práctica en las
 
SILABO DE DEONTOLOGIA JURIDICA
SILABO DE DEONTOLOGIA JURIDICASILABO DE DEONTOLOGIA JURIDICA
SILABO DE DEONTOLOGIA JURIDICA
 
Aprende a elegir tu talla y medir correctamente ARDYSS
Aprende a elegir tu talla y medir correctamente ARDYSSAprende a elegir tu talla y medir correctamente ARDYSS
Aprende a elegir tu talla y medir correctamente ARDYSS
 
E cap 1- projeto-conceitos, atribuições e responsabilidade
E cap 1- projeto-conceitos, atribuições e responsabilidadeE cap 1- projeto-conceitos, atribuições e responsabilidade
E cap 1- projeto-conceitos, atribuições e responsabilidade
 
Ensayo para clase derecho
Ensayo para clase derechoEnsayo para clase derecho
Ensayo para clase derecho
 
E cap 8- dimensionamento de eletrodutos
E cap 8- dimensionamento de eletrodutosE cap 8- dimensionamento de eletrodutos
E cap 8- dimensionamento de eletrodutos
 
Shampoo y acondicionador
Shampoo y acondicionadorShampoo y acondicionador
Shampoo y acondicionador
 
Cultura digital - Aula 1
Cultura digital - Aula 1Cultura digital - Aula 1
Cultura digital - Aula 1
 
El mundo Globalizado
El mundo GlobalizadoEl mundo Globalizado
El mundo Globalizado
 
Ensayo sobre derechos humanos y garantías constitucionales
Ensayo sobre derechos humanos y garantías constitucionalesEnsayo sobre derechos humanos y garantías constitucionales
Ensayo sobre derechos humanos y garantías constitucionales
 
Sudoku
SudokuSudoku
Sudoku
 

Semelhante a DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the generics?

响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
Discover The Unknown Flex 4.5 (MAX 2011)
Discover The Unknown Flex 4.5 (MAX 2011)Discover The Unknown Flex 4.5 (MAX 2011)
Discover The Unknown Flex 4.5 (MAX 2011)Piotr Walczyszyn
 
Clojure: Towards The Essence of Programming
Clojure: Towards The Essence of ProgrammingClojure: Towards The Essence of Programming
Clojure: Towards The Essence of ProgrammingHoward Lewis Ship
 
The Python bites your apple
The Python bites your appleThe Python bites your apple
The Python bites your appleQidan He
 
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)Theo Jungeblut
 
Verilog overview
Verilog overviewVerilog overview
Verilog overviewposdege
 
UNICORN: A Unified Approach for Localizing Non-deadlock Concurrency Bugs
UNICORN: A Unified Approach for Localizing Non-deadlock Concurrency BugsUNICORN: A Unified Approach for Localizing Non-deadlock Concurrency Bugs
UNICORN: A Unified Approach for Localizing Non-deadlock Concurrency BugsSangmin Park
 
Building Hierarchy
Building HierarchyBuilding Hierarchy
Building HierarchyMohamed Samy
 
Safe navigation in OCL
Safe navigation in OCLSafe navigation in OCL
Safe navigation in OCLEdward Willink
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16Max Kleiner
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
 
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupJava 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupHenri Tremblay
 
PATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and JavaPATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and JavaMichael Heron
 

Semelhante a DevoxxFR 2013: Lambda are coming. Meanwhile, are you sure we've mastered the generics? (20)

EMFPath
EMFPathEMFPath
EMFPath
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Taming Asynchrony using RxJS
Taming Asynchrony using RxJSTaming Asynchrony using RxJS
Taming Asynchrony using RxJS
 
Discover The Unknown Flex 4.5 (MAX 2011)
Discover The Unknown Flex 4.5 (MAX 2011)Discover The Unknown Flex 4.5 (MAX 2011)
Discover The Unknown Flex 4.5 (MAX 2011)
 
C# in depth
C# in depthC# in depth
C# in depth
 
Clojure: Towards The Essence of Programming
Clojure: Towards The Essence of ProgrammingClojure: Towards The Essence of Programming
Clojure: Towards The Essence of Programming
 
Codemash-Clojure.pdf
Codemash-Clojure.pdfCodemash-Clojure.pdf
Codemash-Clojure.pdf
 
The Python bites your apple
The Python bites your appleThe Python bites your apple
The Python bites your apple
 
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
 
京都Gtugコンパチapi
京都Gtugコンパチapi京都Gtugコンパチapi
京都Gtugコンパチapi
 
Verilog overview
Verilog overviewVerilog overview
Verilog overview
 
UNICORN: A Unified Approach for Localizing Non-deadlock Concurrency Bugs
UNICORN: A Unified Approach for Localizing Non-deadlock Concurrency BugsUNICORN: A Unified Approach for Localizing Non-deadlock Concurrency Bugs
UNICORN: A Unified Approach for Localizing Non-deadlock Concurrency Bugs
 
Building Hierarchy
Building HierarchyBuilding Hierarchy
Building Hierarchy
 
Error handling
Error handlingError handling
Error handling
 
Safe navigation in OCL
Safe navigation in OCLSafe navigation in OCL
Safe navigation in OCL
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupJava 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
 
PATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and JavaPATTERNS09 - Generics in .NET and Java
PATTERNS09 - Generics in .NET and Java
 

Mais 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
 
Generics and Lambda survival guide - DevNexus 2017
Generics and Lambda survival guide - DevNexus 2017Generics and Lambda survival guide - DevNexus 2017
Generics and Lambda survival guide - DevNexus 2017Henri Tremblay
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingHenri 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
 
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
 
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
 
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
 
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
 

Mais de Henri Tremblay (16)

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
 
Generics and Lambda survival guide - DevNexus 2017
Generics and Lambda survival guide - DevNexus 2017Generics and Lambda survival guide - DevNexus 2017
Generics and Lambda survival guide - DevNexus 2017
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
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
 
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
 
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
 
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
 
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 generics?

  • 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. Henri Tremblay OCTO Technology Open Source Responsable R&D EasyMock Performance Objenesis Calcul parallèle
  • 6.
  • 7. What do I need to know? Why © OCTO 2011 7
  • 8. What do I need to know? Why Covariance © OCTO 2011 8
  • 9. What do I need to know? Why Covariance Capture © OCTO 2011 9
  • 10. What do I need to know? Why Covariance Capture Erasure © OCTO 2011 10
  • 11. What do I need to know? Why Covariance Capture Erasure Bridge © OCTO 2011 11
  • 12. What do I need to know? Why Covariance Capture Erasure Bridge © OCTO 2011 12
  • 13. Lambda return Tweet.TWEETS.stream() .collect(Collectors .groupingBy(t->t.containsHashTag("#lambda"), HashMap::new, ArrayList::new));
  • 14. 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);
  • 15. Lambda = Inférence return Tweet.TWEETS.stream() .collect( Collectors .groupingBy(t->t.containsHashTag("#lambda"), HashMap::new, ArrayList::new));
  • 16. 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> © OCTO 2011 16
  • 17. Ostrich defense @SuppressWarnings("unchecked") © OCTO 2011 17
  • 19. Rule #1 A code compiling without warning should never ever cause a ClassCastException © OCTO 2011 19
  • 21. Capture usually is Type List<?> bar(); <T> IExpectationSetters<T> expect(T value); void andReturn(T value); // Method of IExpectationSetters Returns a capture#6 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>) © OCTO 2011 21
  • 22. Only solution We need to cast expect((List<String>) bar()).andReturn(new ArrayList<String>()); Tell to expect we want a 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 © OCTO 2011 22
  • 23. How the compiler tells the type Determine The parameter the return value type <T> T anyObject(T clazz) © OCTO 2011 23
  • 24. How the compiler tells the type The assigned Determine the variable return type MyType var = <T> T anyObject() © OCTO 2011 24
  • 25. But watch out with overloading public void foo(String s) public void foo(Object o) foo(anyObject()); Can’t guess the type © OCTO 2011 25
  • 26. Trick #1 Determine the return Artificially give the type with a value type dedicated parameter <T> T anyObject(Class<T> clazz) © OCTO 2011 26
  • 27. But how to pass a generic? public void foo(String s) public void foo(Object o) foo(anyObject(List<String>.class)); Examples: Illegal ToXXXFunction © OCTO 2011 27
  • 28. Example • Collectors.mapping params • Function, Collector • ToIntFunction, Collector.OfInt • ToLongFunction , Collector.OfLong • ToDoubleFunction, , Collector.OfDouble © OCTO 2011 28
  • 29. Some solutions This would work foo((String) anyObject()); foo((List<String>) anyObject()); // Warning But still doesn’t work for generics © OCTO 2011 29
  • 30. Trick #2 So the only solution is foo(EasyMock.<List<String>> anyObject()); … which sadly doesn’t support static imports foo(.<List<String>> anyObject()); // Illegal © OCTO 2011 30
  • 31. 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));
  • 32. Trick #3: Lambda inference Object o = (Runnable) () -> { System.out.println("hi"); }; Collections.sort(strings, (String a, String b) -> a.compareTo(b));
  • 33. Conclusion Who has learned something today? © OCTO 2011 33
  • 34. 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-4.html Everything on generics: http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
  • 35. Conclusion Questions? © OCTO 2011 35