SlideShare a Scribd company logo
1 of 36
#Devoxx
The Sincerest Form of Flattery
Maurice Naftalin José Paumard
@MauriceNaftalin @JosePaumard
#Devoxx @MauriceNaftalin @JosePaumard
Maurice Naftalin
Java 5 Java 8
2013 2014 2015 2017
#Devoxx @MauriceNaftalin @JosePaumard
@JosePaumard
https://josepaumard.github.io https://github.com/JosePaumard
https://www.pluralsight.com/authors/jose-paumard
https://www.slideshare.net/jpaumard
https://www.youtube.com/user/JPaumard
#Devoxx
JAlba
@JAlbaUnconf
https://jalba.scot/
#Devoxx @MauriceNaftalin @JosePaumard
Functional Programming: Elegant,
Mathematically Sound
Higher Order Functions
(Lisp, 1958)
Parametric Polymorphism
(ML, 1975)
Pattern Matching
(Caml, 1985)
But often not practicable
#Devoxx @MauriceNaftalin @JosePaumard
Object-Oriented Languages: Successful
but Envious
From the 1980s, OO languages
dominated
• Subtype Polymorphism, Inheritance
• Strong Static Typing
• Automatic Memory Management
#Devoxx @MauriceNaftalin @JosePaumard
Object-Oriented Languages: Successful
but Envious
From the 1980s, OO languages
dominated
• Subtype Polymorphism, Inheritance
• Strong Static Typing
• Automatic Memory Management
But they always suffered feature envy
#Devoxx @MauriceNaftalin @JosePaumard
So, Pizza!
Java
+
Generics + Higher Order Functions + Pattern-Matching
Pizza =
#DevoxxFR#Devoxx @MauriceNaftalin @JosePaumard
Pizza
(1997)
Generic Java
(1998)
Java 5
(2004)
Scala
(2003)
#Devoxx @MauriceNaftalin @JosePaumard
Java Ate Pizza in Three Courses
- Parametric Polymorphism in 2004
- Higher Order Functions in 2014
- Pattern Matching 20x
#Devoxx @MauriceNaftalin @JosePaumard
Scala Ate Pizza In One Bite
Scala took all of those in 2004
Much earlier than Java!
Because Scala wasn’t hindered by
backward compatibility
#Devoxx @MauriceNaftalin @JosePaumard
Generics: Stating the Problems
Problem 1: Type information availability at runtime
vs.
List<Integer> ints = ...;
Integer[] intArray = ints.toArray();
List<Integer> ints = ...;
Integer[] intArray = ints.toArray(Integer[]::new);
#Devoxx @MauriceNaftalin @JosePaumard
Generics: Stating the Problems
Problem 2: Array subtyping
This code is allowed:
To make this code possible:
Integer[] ints = ...;
Number[] numbers = ints;
Arrays.sort(Object[] objects); // can be called with Integer[]
#Devoxx @MauriceNaftalin @JosePaumard
Generics: Stating the Problems
Problem 2: Array subtyping
But then the problem is: you can write this code:
That throws an ArrayStoreException
Covariance is only good for getting things out from a
container, not putting them in
numbers[0] = 3.14;
#Devoxx @MauriceNaftalin @JosePaumard
Type Erasure in Generic Java
Type erasure consists in replacing the parameter type with its
bound in the class file
Adopted for backwards compatibility with legacy ungenerified
libraries
#Devoxx @MauriceNaftalin @JosePaumard
Type Erasure in Generic Java
There is no T in the class file
public class Holder<T> {
private T t;
public Holder(T t)
public void set(T t)
}
public class Holder {
private Object t;
public Holder(Object t)
public void set(Object t)
}
#Devoxx @MauriceNaftalin @JosePaumard
Type Erasure: How does it Work?
So the compiler is doing the type checking
And it also adds casts when needed
Holder<String> holder = new Holder<String>();
holder.set(10); // Compiler error
String result = holder.get(); String result = (String)holder.get();
#Devoxx @MauriceNaftalin @JosePaumard
Type Erasure vs. Inheritance
How is inheritance handled?
public class StringHolder
extends Holder<String> {
private T t;
public StringHolder(T t) {
...
}
public void set(String s) {
...
}
}
public set(String):void
public synthetic bridge set(Object):void
CHECKCAST String
INVOKEVIRTUAL set(String):void
#Devoxx @MauriceNaftalin @JosePaumard
Type Erasure vs. Inheritance
How is inheritance handled?
public class Holder<T> {
private T t;
public Holder(T t) {
this.t = t;
}
public T get() {
return this.t;
}
}
public class StringHolder
extends Holder<String> {
private T t;
public StringHolder(T t) {
super(t);
}
public String get() {
return super.get();
}
}
#Devoxx @MauriceNaftalin @JosePaumard
How about Arrays?
Suppose the array is an array of generics
It would be nice to have an ArrayStoreException
But the array is in fact an array of erased holders
So… arrays of generics can’t be created in Java
Holder<String>[] stringHolders = new Holder<String>[10];
Object[] objects = stringHolders;
objects[0] = new Holder<Integer>(10); // ArrayStoreException?
#Devoxx @MauriceNaftalin @JosePaumard
How about List in Java?
So covariance is bad, what can we use for collections?
List<Integer> cannot be a subtype of List<Number>
Because we know that this code cannot work
List<Integer> ints = ...;
List<Number> numbers = ints;
numbers.add(3.14d);
#Devoxx @MauriceNaftalin @JosePaumard
How about List?
Now that the type List<Integer> is not
a subtype of List<Number>…
How many sort() methods do we need?
sort(List<Number> numbers)
sort(List<Integer> ints)
... 
#Devoxx @MauriceNaftalin @JosePaumard
Wildcards to the rescue! (really?)
We need a list that accepts Number and any subtype of
Number
So now we have one method
In that case, it is ok for the type to be covariant
List<? extends Number> numbers
sort(List<Number> numbers)
sort(List<Integer> ints)
sort(List<? extends Number> numbers)
#Devoxx @MauriceNaftalin @JosePaumard
Generics in Scala
New language, free of constraints on Java:
• New collections library, defined according to their use:
• Immutable structures can be declared as covariant in their
component type
• Declaration-site variance (also in C# and Kotlin) moves work
from client code to library code
class Pair[+T](val first: T, val second: T)
def toString(p: Pair[AnyVal]){…}
toString(new Pair(1, 2))
toString(new Pair("one", "two"))
#Devoxx @MauriceNaftalin @JosePaumard
Closures in Pizza
Functions as first-class citizens: the essence of FP
Higher-order functions originally from l-calculus / LISP
max(List<S>, (S, S) => boolean) => S
max(List.of("one", "three"), (s0, s1) -> s0.length() > s1.length())
// returns "three"
#Devoxx @MauriceNaftalin @JosePaumard
Closures in Pizza
How to include in Java, which does not have explicit function
types?
Solution: for each function, create an abstract class with an
apply method.
Capture non-final local variables? They sat on the fence!
#Devoxx @MauriceNaftalin @JosePaumard
Closures Lambdas in Java
2006 debate over whether to introduce a function type.
Eventually resolved in favour of using a Single Abstract
Method Interface (Functional Interface)
No change in the type system: it preserves the nominal typing
and simplicity of language
Capture of non-final local variables prevented, to preserve
thread safety
#Devoxx @MauriceNaftalin @JosePaumard
Closures in Scala
Function types (structural) fundamental element of the type
system.
Closures in Scala can capture vars
How does it work with concurrency?
Short answer: it does not
#Devoxx @MauriceNaftalin @JosePaumard
Partial Application in Scala
One fundamental operation in Functional Programming is
Partial Application, achieved by currying
def partialApplication(bi: (String, String) => Int, word: String) {
return s => bi(word, s)
}
val bi: = (word: String, s: String) => word.indexOf(s)
val f: String => Integer = partialApplication(_.indexOf(_), "Hello")
val bi: = (word: String)(s: String) => word.indexOf(s)
val f: String => Integer = bi("Hello")
#Devoxx @MauriceNaftalin @JosePaumard
Partial Application in Java
The same thing is done in Java with bound method
references
Function<String, Integer> partialApplication(
BiFunction<String, String, Integer> biFunction, String word) {
return s -> bi.apply(word, s);
}
BiFunction<String, String, Integer> bi = (word, s) -> word.indexOf(s);
var f = partialApplication(String::indexOf, "Hello");
Function<String, Integer> f = "Hello"::indexOf;
#Devoxx @MauriceNaftalin @JosePaumard
Pattern Matching in Pizza
Just a switch on types already with deconstruction
class Vehicle {
case Car(String color);
case Bus();
}
static int capacity(Vehicle vehicle) {
switch(vehicle) {
case Car(color):
return "red".equals(color)? 20: 4;
case Bus:
return 12;
}
}
#Devoxx @MauriceNaftalin @JosePaumard
Pattern Matching in Scala
Match expression on types with deconstruction,
no exhaustiveness check
sealed trait Vehicle;
case class Car(String color) extends Vehicle
case object Bus extends Vehicle
def capacity(vehicle: Vehicle) {
return vehicle match {
case Car(color) => "red".equals(color)? 20: 4
case Bus => 12
}
}
#Devoxx @MauriceNaftalin @JosePaumard
Pattern Matching in Java
Switch expression on types with deconstruction and
exhaustiveness check
sealed interface Vehicle {
record Car(String color) implements Vehicle {}
static class Bus implements Vehicle {}
}
static int capacity(Vehicle vehicle) {
return switch(vehicle) {
case Car("red") -> 20;
case Car(var color) -> 4;
case Bus -> 12;
};
}
#Devoxx @MauriceNaftalin @JosePaumard
Conclusion
Language design is really complicated!
Backwards compatibility makes it even more complicated
Java has to take it very seriously
Scala has chosen fast language evolution over backwards
compatibility
Both viewpoints have their advantage!
#Devoxx @MauriceNaftalin @JosePaumard
Conclusion
« We don’t want to be the first to
include a feature, because every
feature we add will never be
removed »
Brian Goetz,
Java Language Architect
#Devoxx
Thank you!
Maurice Naftalin José Paumard
@mauricenaftalin @JosePaumard

More Related Content

What's hot

Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven edition
José Paumard
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 

What's hot (20)

Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
Going reactive in java
Going reactive in javaGoing reactive in java
Going reactive in java
 
Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven edition
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developers
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Java 8 Streams and Rx Java Comparison
Java 8 Streams and Rx Java ComparisonJava 8 Streams and Rx Java Comparison
Java 8 Streams and Rx Java Comparison
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
JFokus 50 new things with java 8
JFokus 50 new things with java 8JFokus 50 new things with java 8
JFokus 50 new things with java 8
 
python.ppt
python.pptpython.ppt
python.ppt
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
Autumn collection JavaOne 2014
Autumn collection JavaOne 2014Autumn collection JavaOne 2014
Autumn collection JavaOne 2014
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Python
PythonPython
Python
 

Similar to The Sincerest Form of Flattery

Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
sagaroceanic11
 

Similar to The Sincerest Form of Flattery (20)

Javaslang @ Devoxx
Javaslang @ DevoxxJavaslang @ Devoxx
Javaslang @ Devoxx
 
Beauty & the Beast - Java VS TypeScript
Beauty & the Beast - Java VS TypeScriptBeauty & the Beast - Java VS TypeScript
Beauty & the Beast - Java VS TypeScript
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Hipster oriented programming (Mobilization Lodz 2015)
Hipster oriented programming (Mobilization Lodz 2015)Hipster oriented programming (Mobilization Lodz 2015)
Hipster oriented programming (Mobilization Lodz 2015)
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developers
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About Morphisms
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresque
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
SPARQL introduction and training (130+ slides with exercices)
SPARQL introduction and training (130+ slides with exercices)SPARQL introduction and training (130+ slides with exercices)
SPARQL introduction and training (130+ slides with exercices)
 

More from José Paumard

More from José Paumard (15)

Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdf
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern Matching
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
 
Designing functional and fluent API: application to some GoF patterns
Designing functional and fluent API: application to some GoF patternsDesigning functional and fluent API: application to some GoF patterns
Designing functional and fluent API: application to some GoF patterns
 
Designing functional and fluent API: example of the Visitor Pattern
Designing functional and fluent API: example of the Visitor PatternDesigning functional and fluent API: example of the Visitor Pattern
Designing functional and fluent API: example of the Visitor Pattern
 
Construire son JDK en 10 étapes
Construire son JDK en 10 étapesConstruire son JDK en 10 étapes
Construire son JDK en 10 étapes
 
Asynchronous Systems with Fn Flow
Asynchronous Systems with Fn FlowAsynchronous Systems with Fn Flow
Asynchronous Systems with Fn Flow
 
JAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) BridgeJAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) Bridge
 
Streams in the wild
Streams in the wildStreams in the wild
Streams in the wild
 
JAX RS and CDI bike the reactive bridge
JAX RS and CDI bike the reactive bridgeJAX RS and CDI bike the reactive bridge
JAX RS and CDI bike the reactive bridge
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses états
 
ArrayList et LinkedList sont dans un bateau
ArrayList et LinkedList sont dans un bateauArrayList et LinkedList sont dans un bateau
ArrayList et LinkedList sont dans un bateau
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
 

Recently uploaded

An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Recently uploaded (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

The Sincerest Form of Flattery

  • 1. #Devoxx The Sincerest Form of Flattery Maurice Naftalin José Paumard @MauriceNaftalin @JosePaumard
  • 2. #Devoxx @MauriceNaftalin @JosePaumard Maurice Naftalin Java 5 Java 8 2013 2014 2015 2017
  • 3. #Devoxx @MauriceNaftalin @JosePaumard @JosePaumard https://josepaumard.github.io https://github.com/JosePaumard https://www.pluralsight.com/authors/jose-paumard https://www.slideshare.net/jpaumard https://www.youtube.com/user/JPaumard
  • 5. #Devoxx @MauriceNaftalin @JosePaumard Functional Programming: Elegant, Mathematically Sound Higher Order Functions (Lisp, 1958) Parametric Polymorphism (ML, 1975) Pattern Matching (Caml, 1985) But often not practicable
  • 6. #Devoxx @MauriceNaftalin @JosePaumard Object-Oriented Languages: Successful but Envious From the 1980s, OO languages dominated • Subtype Polymorphism, Inheritance • Strong Static Typing • Automatic Memory Management
  • 7. #Devoxx @MauriceNaftalin @JosePaumard Object-Oriented Languages: Successful but Envious From the 1980s, OO languages dominated • Subtype Polymorphism, Inheritance • Strong Static Typing • Automatic Memory Management But they always suffered feature envy
  • 8. #Devoxx @MauriceNaftalin @JosePaumard So, Pizza! Java + Generics + Higher Order Functions + Pattern-Matching Pizza =
  • 10. #Devoxx @MauriceNaftalin @JosePaumard Java Ate Pizza in Three Courses - Parametric Polymorphism in 2004 - Higher Order Functions in 2014 - Pattern Matching 20x
  • 11. #Devoxx @MauriceNaftalin @JosePaumard Scala Ate Pizza In One Bite Scala took all of those in 2004 Much earlier than Java! Because Scala wasn’t hindered by backward compatibility
  • 12. #Devoxx @MauriceNaftalin @JosePaumard Generics: Stating the Problems Problem 1: Type information availability at runtime vs. List<Integer> ints = ...; Integer[] intArray = ints.toArray(); List<Integer> ints = ...; Integer[] intArray = ints.toArray(Integer[]::new);
  • 13. #Devoxx @MauriceNaftalin @JosePaumard Generics: Stating the Problems Problem 2: Array subtyping This code is allowed: To make this code possible: Integer[] ints = ...; Number[] numbers = ints; Arrays.sort(Object[] objects); // can be called with Integer[]
  • 14. #Devoxx @MauriceNaftalin @JosePaumard Generics: Stating the Problems Problem 2: Array subtyping But then the problem is: you can write this code: That throws an ArrayStoreException Covariance is only good for getting things out from a container, not putting them in numbers[0] = 3.14;
  • 15. #Devoxx @MauriceNaftalin @JosePaumard Type Erasure in Generic Java Type erasure consists in replacing the parameter type with its bound in the class file Adopted for backwards compatibility with legacy ungenerified libraries
  • 16. #Devoxx @MauriceNaftalin @JosePaumard Type Erasure in Generic Java There is no T in the class file public class Holder<T> { private T t; public Holder(T t) public void set(T t) } public class Holder { private Object t; public Holder(Object t) public void set(Object t) }
  • 17. #Devoxx @MauriceNaftalin @JosePaumard Type Erasure: How does it Work? So the compiler is doing the type checking And it also adds casts when needed Holder<String> holder = new Holder<String>(); holder.set(10); // Compiler error String result = holder.get(); String result = (String)holder.get();
  • 18. #Devoxx @MauriceNaftalin @JosePaumard Type Erasure vs. Inheritance How is inheritance handled? public class StringHolder extends Holder<String> { private T t; public StringHolder(T t) { ... } public void set(String s) { ... } } public set(String):void public synthetic bridge set(Object):void CHECKCAST String INVOKEVIRTUAL set(String):void
  • 19. #Devoxx @MauriceNaftalin @JosePaumard Type Erasure vs. Inheritance How is inheritance handled? public class Holder<T> { private T t; public Holder(T t) { this.t = t; } public T get() { return this.t; } } public class StringHolder extends Holder<String> { private T t; public StringHolder(T t) { super(t); } public String get() { return super.get(); } }
  • 20. #Devoxx @MauriceNaftalin @JosePaumard How about Arrays? Suppose the array is an array of generics It would be nice to have an ArrayStoreException But the array is in fact an array of erased holders So… arrays of generics can’t be created in Java Holder<String>[] stringHolders = new Holder<String>[10]; Object[] objects = stringHolders; objects[0] = new Holder<Integer>(10); // ArrayStoreException?
  • 21. #Devoxx @MauriceNaftalin @JosePaumard How about List in Java? So covariance is bad, what can we use for collections? List<Integer> cannot be a subtype of List<Number> Because we know that this code cannot work List<Integer> ints = ...; List<Number> numbers = ints; numbers.add(3.14d);
  • 22. #Devoxx @MauriceNaftalin @JosePaumard How about List? Now that the type List<Integer> is not a subtype of List<Number>… How many sort() methods do we need? sort(List<Number> numbers) sort(List<Integer> ints) ... 
  • 23. #Devoxx @MauriceNaftalin @JosePaumard Wildcards to the rescue! (really?) We need a list that accepts Number and any subtype of Number So now we have one method In that case, it is ok for the type to be covariant List<? extends Number> numbers sort(List<Number> numbers) sort(List<Integer> ints) sort(List<? extends Number> numbers)
  • 24. #Devoxx @MauriceNaftalin @JosePaumard Generics in Scala New language, free of constraints on Java: • New collections library, defined according to their use: • Immutable structures can be declared as covariant in their component type • Declaration-site variance (also in C# and Kotlin) moves work from client code to library code class Pair[+T](val first: T, val second: T) def toString(p: Pair[AnyVal]){…} toString(new Pair(1, 2)) toString(new Pair("one", "two"))
  • 25. #Devoxx @MauriceNaftalin @JosePaumard Closures in Pizza Functions as first-class citizens: the essence of FP Higher-order functions originally from l-calculus / LISP max(List<S>, (S, S) => boolean) => S max(List.of("one", "three"), (s0, s1) -> s0.length() > s1.length()) // returns "three"
  • 26. #Devoxx @MauriceNaftalin @JosePaumard Closures in Pizza How to include in Java, which does not have explicit function types? Solution: for each function, create an abstract class with an apply method. Capture non-final local variables? They sat on the fence!
  • 27. #Devoxx @MauriceNaftalin @JosePaumard Closures Lambdas in Java 2006 debate over whether to introduce a function type. Eventually resolved in favour of using a Single Abstract Method Interface (Functional Interface) No change in the type system: it preserves the nominal typing and simplicity of language Capture of non-final local variables prevented, to preserve thread safety
  • 28. #Devoxx @MauriceNaftalin @JosePaumard Closures in Scala Function types (structural) fundamental element of the type system. Closures in Scala can capture vars How does it work with concurrency? Short answer: it does not
  • 29. #Devoxx @MauriceNaftalin @JosePaumard Partial Application in Scala One fundamental operation in Functional Programming is Partial Application, achieved by currying def partialApplication(bi: (String, String) => Int, word: String) { return s => bi(word, s) } val bi: = (word: String, s: String) => word.indexOf(s) val f: String => Integer = partialApplication(_.indexOf(_), "Hello") val bi: = (word: String)(s: String) => word.indexOf(s) val f: String => Integer = bi("Hello")
  • 30. #Devoxx @MauriceNaftalin @JosePaumard Partial Application in Java The same thing is done in Java with bound method references Function<String, Integer> partialApplication( BiFunction<String, String, Integer> biFunction, String word) { return s -> bi.apply(word, s); } BiFunction<String, String, Integer> bi = (word, s) -> word.indexOf(s); var f = partialApplication(String::indexOf, "Hello"); Function<String, Integer> f = "Hello"::indexOf;
  • 31. #Devoxx @MauriceNaftalin @JosePaumard Pattern Matching in Pizza Just a switch on types already with deconstruction class Vehicle { case Car(String color); case Bus(); } static int capacity(Vehicle vehicle) { switch(vehicle) { case Car(color): return "red".equals(color)? 20: 4; case Bus: return 12; } }
  • 32. #Devoxx @MauriceNaftalin @JosePaumard Pattern Matching in Scala Match expression on types with deconstruction, no exhaustiveness check sealed trait Vehicle; case class Car(String color) extends Vehicle case object Bus extends Vehicle def capacity(vehicle: Vehicle) { return vehicle match { case Car(color) => "red".equals(color)? 20: 4 case Bus => 12 } }
  • 33. #Devoxx @MauriceNaftalin @JosePaumard Pattern Matching in Java Switch expression on types with deconstruction and exhaustiveness check sealed interface Vehicle { record Car(String color) implements Vehicle {} static class Bus implements Vehicle {} } static int capacity(Vehicle vehicle) { return switch(vehicle) { case Car("red") -> 20; case Car(var color) -> 4; case Bus -> 12; }; }
  • 34. #Devoxx @MauriceNaftalin @JosePaumard Conclusion Language design is really complicated! Backwards compatibility makes it even more complicated Java has to take it very seriously Scala has chosen fast language evolution over backwards compatibility Both viewpoints have their advantage!
  • 35. #Devoxx @MauriceNaftalin @JosePaumard Conclusion « We don’t want to be the first to include a feature, because every feature we add will never be removed » Brian Goetz, Java Language Architect
  • 36. #Devoxx Thank you! Maurice Naftalin José Paumard @mauricenaftalin @JosePaumard

Editor's Notes

  1. This mismatch between languages is ironic, Java supports polymorphic arrays as best as it can, as a result Pizza must offer less good support for them
  2. This mismatch between languages is ironic, Java supports polymorphic arrays as best as it can, as a result Pizza must offer less good support for them
  3. HALF WAY
  4. 35 mins