SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
The Future of Java: Records, Sealed Classes
and Pattern Matching
Among other things
José Paumard
Java Developer Advocate
Java Platform Group
https://twitter.com/JosePaumard
https://github.com/JosePaumard
https://www.youtube.com/user/java
https://www.youtube.com/user/JPaumard
https://www.youtube.com/hashtag/jepcafe
https://fr.slideshare.net/jpaumard
https://www.pluralsight.com/authors/jose-
paumard
https://dev.ja
va
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
3
Dev.java
Java 8 Java 11
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
4
Java 17 – LTS!
Java 8 Java 11
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
5
Java 17 – LTS!
Java 8
Java 11
Java 17 ?
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
6
Next LTS: Java 21
Java 8
Java 11
Java 17
Java 21
Language
Type inference for locals (var)
Switch expressions
Text blocks
Record classes
Sealed classes
Pattern matching for instanceof
Compact String, Indify
Concatenation
JDK 17: New Features Since the JDK 8
Copyright © 2021, Oracle and/or its affiliates
7
Tools
jshell
jlink
jdeps
jpackage
java source code launcher
javadoc search + API history
JVM
Garbage Collectors: G1, ZGC
AArch64 support: Windows, Mac, Linux
Docker awareness
Class Data Sharing by default
Helpful NullPointerExceptions
Hidden classes
Libraries
HTTP client
Collection factories
Unix-domain sockets
Stack walker
Deserialization filtering
Pseudo-RNG, SHA-3, TLS 1.3
3/11/2022
Copyright © 2021, Oracle and/or its affiliates | Confidential: Internal/Restricted/Highly Restricted
8
Stop doing that!
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
9
Do not call new Integer(...)
Stop Calling Wrapper Classes Constructors!
@Deprecated(since="9", forRemoval = true)
public Integer(int value) {
this.value = value;
}
@IntrinsicCandidate
public static Integer valueOf(int i) {
// some code
return new Integer(i);
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
10
Do not override finalize()
Stop Overriding Finalize!
@Deprecated(since="9")
protected void finalize() throws Throwable {
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates | Confidential: Internal/Restricted/Highly Restricted
11
Records
?Record and Array Pattern Matching?
Record
Sealed Classes
Switch Expression
Constant Dynamic
Inner Classes
private in VM
Nestmates
Pattern Matching for instanceof
11
14
16
17 Switch on Patterns
19
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
13
In reference to the Amber
Chronicles by Roger Zelazny
Project Amber
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
14
Record Deconstruction
if (o instanceof Rectangle rectangle) {
int width = rectangle.width();
int height = rectangle.height();
// do something with width and height
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
15
This is record deconstruction
width are height are binding variables
Record Deconstruction
if (o instanceof Rectangle(int width, int height)) {
// do something with width and height
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
16
Three type patterns
Three pattern binding variables
One target operand
Pattern Matching for Switch
String formatted =
switch(number) {
case Integer i -> String.format("int %d", i);
case Long l -> String.format("long %d", l);
case Double d -> String.format("double %d", d);
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
17
Pattern Matching for Switch
record Square(int edge) {}
record Circle(int radius) {}
double area = switch(shape) {
case Square(int edge) -> edge* edge;
case Circle(int radius) -> Math.PI*radius*radius;
default -> ...;
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
18
Array Pattern Matching
if (o instanceof String[] array && array.length() >= 2) {
// do something with array[0] and array[1]
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
19
Array Pattern Matching
if (o instanceof String[] {String s1, String s2}) {
// do something with s1 and s2
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
20
Array Pattern Matching
if (o instanceof Circle[] {Circle(var r1), Circle(var r3)}) {
// do something with r1 and r2
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
21
You can use var in patterns
Syntaxic Sugars
if (shape instanceof Circle(var center, var radius)) {
// center and radius are binding variables
}
record Point(int x, int y) {}
record Circle(Point center, int radius) implements Shape {}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
22
You can tell that you do not need a binding variable
Syntaxic Sugars
if (shape instanceof Circle(var center, _)) {
// center and radius are binding variables
}
record Point(int x, int y) {}
record Circle(Point center, int radius) implements Shape {}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
23
You can nest patterns (nested patterns)
Syntaxic Sugars
if (shape instanceof Circle(var center, _) &&
center instanceof Point(int x, int y)) {
// center and radius are binding variables
}
if (shape instanceof Circle(Point(int x, int y), _)) {
// center and radius are binding variables
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
24
The deconstruction uses the canonical constructor of a
record
What about:
- factory methods?
- classes that are not records?
Deconstruction
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
25
Deconstruction Using Factory Methods
interface Shape {
static Circle circle(double radius) {
return new Circle(radius);
}
static Square square(double edge) {
return new Square(edge);
}
}
record Circle(double radius) {}
record Square(double edge) {}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
26
Then this code becomes possible:
Deconstruction Using Factory Methods
double area = switch(shape) {
case Shape.circle(double radius) -> Math.PI*radius*radius;
case Shape.square(double edge) -> edge*edge;
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
27
What About Your POJOs?
public class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public deconstructor(int x, int y) {
x = this.x;
y = this.y;
}
}
The binding variables
are the same
external state
description
Allows defensive copy
and overloading
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
28
You saw patterns with instanceof and switch
Let us see match !
Pattern with Match
record Point(int x, int y) {}
record Circle(Point center, int radius) implements Shape {}
Circle circle = ...;
match Circle(var center, var radius) = circle;
// center and radius are binding variables
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
29
If shape is in fact a rectangle…
You can throw an exception
Pattern with Match
Shape shape = ...;
match Circle(var center, var radius) = shape
else
throw new IllegalStateException("Not a circle");
// center and radius are binding variables
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
30
If shape is in fact a rectangle …
Or define default values
Pattern with Match
Shape shape = ...;
match Circle(Point center, int radius) = shape
else {
center = new Point(0, 0); // this is called
radius = 1d; // an anonymous matcher
}
// center and radius are binding variables
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
31
You can use match with more than one pattern…
… or use nested patterns
Pattern with Match
Shape shape = ...;
match Rectangle(var p1, var p2) = shape,
Point(var x0, var y0) = p1,
Point(var x1, var y2) = p2;
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
32
With factory methods
More Examples
if (opt instanceof Optional.of(var max)) {
// max is a binding variable
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
33
With factory methods
More Examples
if (s instanceof
String.format("%s is %d years old",
String name, Integer.valueOf(int age) {
// name and age are binding variables
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
34
You can create maps with factory methods
This is an extended form of Pattern Matching where you
check the value of a binding variable
More Examples
if (map instanceof Map.withMapping("name", var name) &&
map instanceof Map.withMapping("email", var email)) {
// name and email are binding variables
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
35
Pattern combination
More Examples
if (map instanceof Map.withMapping("name", var name) __AND
map instanceof Map.withMapping("email", var email)) {
// name and email are binding variables
}
__AND = pattern combination
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
36
More Examples
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address" : {
"street": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
}
}
if (json instanceof
stringKey("firstName", var firstName) __AND
stringKey("lastName", var lastName) __AND
intKey("age", var age) __AND
objectKey("address",
stringKey("stree", var street) __AND
stringKey("city", var city) __AND
stringKey("state", var state)
)) {
// firstName, lastName, age,
// street, city, state, ...
// are binding variables
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
37
If Java Embraces « Map Literals »
Map<String, String> map = {
"firstName": "John",
"lastName": "Smith",
"age": "25"
}
if (map instanceof
{
"firstName": var firstName,
"lastName": var lastName,
"age": Integer.toString(var age)
}) {
// firstName, lastName, age
// are binding variables
}
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
38
• Constant Patterns: checks the operand with a constant
value
• Type Patterns: checks if the operand has the right type,
casts it, and creates a binding variable
Patterns at a Glance
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
39
• Patterns + Deconstruction: checks the operand type,
casts it, bind the component to binding variables
• Patterns + Method: uses a factory method or a
deconstructor
• Patterns + Var: infers the right type, and creates the
binding variable
• Pattern + _: infers the right type, but does not create
the binding variable
Patterns at a Glance
3/11/2022
Copyright © 2021, Oracle and/or its affiliates |
40
Where are we?
• Pattern Matching for instanceof
• Pattern Matching for Switch
• Record and Array Pattern Matching
• Match
• Literals
Patterns at a Glance

Contenu connexe

Tendances

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 

Tendances (20)

Web Service Presentation
Web Service PresentationWeb Service Presentation
Web Service Presentation
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
An in Depth Journey into Odoo's ORM
An in Depth Journey into Odoo's ORMAn in Depth Journey into Odoo's ORM
An in Depth Journey into Odoo's ORM
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of Purity
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
 
Introduce yourself to java 17
Introduce yourself to java 17Introduce yourself to java 17
Introduce yourself to java 17
 
Methods and constructors in java
Methods and constructors in javaMethods and constructors in java
Methods and constructors in java
 
Clean code
Clean code Clean code
Clean code
 
Introduction to graphQL
Introduction to graphQLIntroduction to graphQL
Introduction to graphQL
 
OpenId Connect Protocol
OpenId Connect ProtocolOpenId Connect Protocol
OpenId Connect Protocol
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
TypeScript Seminar
TypeScript SeminarTypeScript Seminar
TypeScript Seminar
 
10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]
 

Similaire à The Future of Java: Records, Sealed Classes and Pattern Matching

breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
VishalKumarJha10
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
vmandrychenko
 
SECTION D2)Display the item number and total cost for each order l.docx
SECTION D2)Display the item number and total cost for each order l.docxSECTION D2)Display the item number and total cost for each order l.docx
SECTION D2)Display the item number and total cost for each order l.docx
kenjordan97598
 
10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf
10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf
10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf
RihabBENLAMINE
 

Similaire à The Future of Java: Records, Sealed Classes and Pattern Matching (20)

Building data fusion surrogate models for spacecraft aerodynamic problems wit...
Building data fusion surrogate models for spacecraft aerodynamic problems wit...Building data fusion surrogate models for spacecraft aerodynamic problems wit...
Building data fusion surrogate models for spacecraft aerodynamic problems wit...
 
Object - Oriented Programming: Inheritance
Object - Oriented Programming: InheritanceObject - Oriented Programming: Inheritance
Object - Oriented Programming: Inheritance
 
ON SOME FIXED POINT RESULTS IN GENERALIZED METRIC SPACE WITH SELF MAPPINGS UN...
ON SOME FIXED POINT RESULTS IN GENERALIZED METRIC SPACE WITH SELF MAPPINGS UN...ON SOME FIXED POINT RESULTS IN GENERALIZED METRIC SPACE WITH SELF MAPPINGS UN...
ON SOME FIXED POINT RESULTS IN GENERALIZED METRIC SPACE WITH SELF MAPPINGS UN...
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
JS Fest 2018. Виталий Ратушный. ES X
JS Fest 2018. Виталий Ратушный. ES XJS Fest 2018. Виталий Ратушный. ES X
JS Fest 2018. Виталий Ратушный. ES X
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
 
SECTION D2)Display the item number and total cost for each order l.docx
SECTION D2)Display the item number and total cost for each order l.docxSECTION D2)Display the item number and total cost for each order l.docx
SECTION D2)Display the item number and total cost for each order l.docx
 
6-TDD
6-TDD6-TDD
6-TDD
 
JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020
 
10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf
10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf
10_interfacesjavaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf
 
Ch3
Ch3Ch3
Ch3
 
On best one sided approximation by multivariate lagrange
      On best one sided approximation by multivariate lagrange      On best one sided approximation by multivariate lagrange
On best one sided approximation by multivariate lagrange
 
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of TonguesChoose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
 
Java
JavaJava
Java
 
ch3.ppt
ch3.pptch3.ppt
ch3.ppt
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
ch3.ppt
ch3.pptch3.ppt
ch3.ppt
 
ch3.ppt
ch3.pptch3.ppt
ch3.ppt
 
Ch 3.pdf
Ch 3.pdfCh 3.pdf
Ch 3.pdf
 

Plus de José Paumard

Plus de José Paumard (20)

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
 
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
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
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
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Asynchronous Systems with Fn Flow
Asynchronous Systems with Fn FlowAsynchronous Systems with Fn Flow
Asynchronous Systems with Fn Flow
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
 
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
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
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
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
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
 
Linked to ArrayList: the full story
Linked to ArrayList: the full storyLinked to ArrayList: the full story
Linked to ArrayList: the full story
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
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
 

Dernier

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
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
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Dernier (20)

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...
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
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
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
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
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
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
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
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
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.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
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 

The Future of Java: Records, Sealed Classes and Pattern Matching

  • 1. The Future of Java: Records, Sealed Classes and Pattern Matching Among other things José Paumard Java Developer Advocate Java Platform Group
  • 3. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 3 Dev.java Java 8 Java 11
  • 4. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 4 Java 17 – LTS! Java 8 Java 11
  • 5. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 5 Java 17 – LTS! Java 8 Java 11 Java 17 ?
  • 6. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 6 Next LTS: Java 21 Java 8 Java 11 Java 17 Java 21
  • 7. Language Type inference for locals (var) Switch expressions Text blocks Record classes Sealed classes Pattern matching for instanceof Compact String, Indify Concatenation JDK 17: New Features Since the JDK 8 Copyright © 2021, Oracle and/or its affiliates 7 Tools jshell jlink jdeps jpackage java source code launcher javadoc search + API history JVM Garbage Collectors: G1, ZGC AArch64 support: Windows, Mac, Linux Docker awareness Class Data Sharing by default Helpful NullPointerExceptions Hidden classes Libraries HTTP client Collection factories Unix-domain sockets Stack walker Deserialization filtering Pseudo-RNG, SHA-3, TLS 1.3
  • 8. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | Confidential: Internal/Restricted/Highly Restricted 8 Stop doing that!
  • 9. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 9 Do not call new Integer(...) Stop Calling Wrapper Classes Constructors! @Deprecated(since="9", forRemoval = true) public Integer(int value) { this.value = value; } @IntrinsicCandidate public static Integer valueOf(int i) { // some code return new Integer(i); }
  • 10. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 10 Do not override finalize() Stop Overriding Finalize! @Deprecated(since="9") protected void finalize() throws Throwable { }
  • 11. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | Confidential: Internal/Restricted/Highly Restricted 11 Records
  • 12. ?Record and Array Pattern Matching? Record Sealed Classes Switch Expression Constant Dynamic Inner Classes private in VM Nestmates Pattern Matching for instanceof 11 14 16 17 Switch on Patterns 19
  • 13. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 13 In reference to the Amber Chronicles by Roger Zelazny Project Amber
  • 14. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 14 Record Deconstruction if (o instanceof Rectangle rectangle) { int width = rectangle.width(); int height = rectangle.height(); // do something with width and height }
  • 15. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 15 This is record deconstruction width are height are binding variables Record Deconstruction if (o instanceof Rectangle(int width, int height)) { // do something with width and height }
  • 16. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 16 Three type patterns Three pattern binding variables One target operand Pattern Matching for Switch String formatted = switch(number) { case Integer i -> String.format("int %d", i); case Long l -> String.format("long %d", l); case Double d -> String.format("double %d", d); }
  • 17. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 17 Pattern Matching for Switch record Square(int edge) {} record Circle(int radius) {} double area = switch(shape) { case Square(int edge) -> edge* edge; case Circle(int radius) -> Math.PI*radius*radius; default -> ...; }
  • 18. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 18 Array Pattern Matching if (o instanceof String[] array && array.length() >= 2) { // do something with array[0] and array[1] }
  • 19. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 19 Array Pattern Matching if (o instanceof String[] {String s1, String s2}) { // do something with s1 and s2 }
  • 20. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 20 Array Pattern Matching if (o instanceof Circle[] {Circle(var r1), Circle(var r3)}) { // do something with r1 and r2 }
  • 21. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 21 You can use var in patterns Syntaxic Sugars if (shape instanceof Circle(var center, var radius)) { // center and radius are binding variables } record Point(int x, int y) {} record Circle(Point center, int radius) implements Shape {}
  • 22. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 22 You can tell that you do not need a binding variable Syntaxic Sugars if (shape instanceof Circle(var center, _)) { // center and radius are binding variables } record Point(int x, int y) {} record Circle(Point center, int radius) implements Shape {}
  • 23. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 23 You can nest patterns (nested patterns) Syntaxic Sugars if (shape instanceof Circle(var center, _) && center instanceof Point(int x, int y)) { // center and radius are binding variables } if (shape instanceof Circle(Point(int x, int y), _)) { // center and radius are binding variables }
  • 24. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 24 The deconstruction uses the canonical constructor of a record What about: - factory methods? - classes that are not records? Deconstruction
  • 25. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 25 Deconstruction Using Factory Methods interface Shape { static Circle circle(double radius) { return new Circle(radius); } static Square square(double edge) { return new Square(edge); } } record Circle(double radius) {} record Square(double edge) {}
  • 26. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 26 Then this code becomes possible: Deconstruction Using Factory Methods double area = switch(shape) { case Shape.circle(double radius) -> Math.PI*radius*radius; case Shape.square(double edge) -> edge*edge; }
  • 27. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 27 What About Your POJOs? public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public deconstructor(int x, int y) { x = this.x; y = this.y; } } The binding variables are the same external state description Allows defensive copy and overloading
  • 28. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 28 You saw patterns with instanceof and switch Let us see match ! Pattern with Match record Point(int x, int y) {} record Circle(Point center, int radius) implements Shape {} Circle circle = ...; match Circle(var center, var radius) = circle; // center and radius are binding variables
  • 29. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 29 If shape is in fact a rectangle… You can throw an exception Pattern with Match Shape shape = ...; match Circle(var center, var radius) = shape else throw new IllegalStateException("Not a circle"); // center and radius are binding variables
  • 30. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 30 If shape is in fact a rectangle … Or define default values Pattern with Match Shape shape = ...; match Circle(Point center, int radius) = shape else { center = new Point(0, 0); // this is called radius = 1d; // an anonymous matcher } // center and radius are binding variables
  • 31. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 31 You can use match with more than one pattern… … or use nested patterns Pattern with Match Shape shape = ...; match Rectangle(var p1, var p2) = shape, Point(var x0, var y0) = p1, Point(var x1, var y2) = p2;
  • 32. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 32 With factory methods More Examples if (opt instanceof Optional.of(var max)) { // max is a binding variable }
  • 33. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 33 With factory methods More Examples if (s instanceof String.format("%s is %d years old", String name, Integer.valueOf(int age) { // name and age are binding variables }
  • 34. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 34 You can create maps with factory methods This is an extended form of Pattern Matching where you check the value of a binding variable More Examples if (map instanceof Map.withMapping("name", var name) && map instanceof Map.withMapping("email", var email)) { // name and email are binding variables }
  • 35. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 35 Pattern combination More Examples if (map instanceof Map.withMapping("name", var name) __AND map instanceof Map.withMapping("email", var email)) { // name and email are binding variables } __AND = pattern combination
  • 36. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 36 More Examples { "firstName": "John", "lastName": "Smith", "age": 25, "address" : { "street": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" } } if (json instanceof stringKey("firstName", var firstName) __AND stringKey("lastName", var lastName) __AND intKey("age", var age) __AND objectKey("address", stringKey("stree", var street) __AND stringKey("city", var city) __AND stringKey("state", var state) )) { // firstName, lastName, age, // street, city, state, ... // are binding variables }
  • 37. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 37 If Java Embraces « Map Literals » Map<String, String> map = { "firstName": "John", "lastName": "Smith", "age": "25" } if (map instanceof { "firstName": var firstName, "lastName": var lastName, "age": Integer.toString(var age) }) { // firstName, lastName, age // are binding variables }
  • 38. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 38 • Constant Patterns: checks the operand with a constant value • Type Patterns: checks if the operand has the right type, casts it, and creates a binding variable Patterns at a Glance
  • 39. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 39 • Patterns + Deconstruction: checks the operand type, casts it, bind the component to binding variables • Patterns + Method: uses a factory method or a deconstructor • Patterns + Var: infers the right type, and creates the binding variable • Pattern + _: infers the right type, but does not create the binding variable Patterns at a Glance
  • 40. 3/11/2022 Copyright © 2021, Oracle and/or its affiliates | 40 Where are we? • Pattern Matching for instanceof • Pattern Matching for Switch • Record and Array Pattern Matching • Match • Literals Patterns at a Glance