SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Downloaden Sie, um offline zu lesen
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.1
Pattern Matching in Java
Srikanth Sankaran,
Consulting Member of Technical Staff
Java Product Group, Oracle
August 2017
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.2
The following is intended to outline our general product
direction. It is intended for information purposes only,
and may not be incorporated into any contract.
It is not a commitment to deliver any material, code, or
functionality, and should not be relied upon in making
purchasing decisions. The development, release, and
timing of any features or functionality described for
Oracle’s products remains at the sole discretion of
Oracle.
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.3
Pattern Matching - Motivation
if (obj instanceof Integer) {
int intValue = ((Integer) obj).intValue();
// use intValue
}
 Test to see if an expression has some characteristic
 Convert
 Destructure and extract interesting state bits
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.4
Pattern Matching - Motivation
String formatted = "unknown";
if (obj instanceof Integer) {
int i = (Integer) obj;
formatted = String.format("int %d", i);
} else if (obj instanceof Byte) {
byte b = (Byte) obj;
formatted = String.format("byte %d", b);
} else if (obj instanceof Long) {
long l = (Long) obj;
formatted = String.format("long %d", l);
} else if (obj instanceof Double) {
double d = (Double) obj;
formatted = String.format(“double %f", d);
} else if (obj instanceof String) {
String s = (String) obj;
formatted = String.format("String %s", s);
} // ...
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.5
Pattern Matching – Type Test Patterns
 Pattern
– A combination of a predicate applied to a target &
– A set of binding variables extracted from the target if predicate
applies to it.
if (x matches Integer i) {
// can use i here
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.6
Pattern Matching – Type Test Patterns
String formatted = "unknown";
if (obj matches Integer i) {
formatted = String.format("int %d", i);
} else if (obj matches Byte b) {
formatted = String.format("byte %d", b);
} else if (obj matches Long l) {
formatted = String.format("long %d", l);
} else if (obj matches Double d) {
formatted = String.format(“double %f", d);
} else if (obj matches String s) {
formatted = String.format("String %s", s);
} // ...
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.7
Improved Switch
String formatted;
switch (constant) {
case Integer i: formatted = String.format("int %d", i); break;
case Byte b: formatted = String.format(“byte %d",b); break;
case Long l: formatted = String.format(“long %d",l); break;
case Double d: formatted = String.format(“double %f", d); break;
// String, Short, Character, Float, Boolean
default: formatted = "unknown";
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.8
Expression Switch
String formatted =
switch (constant) {
case Integer i -> String.format("int %d", i);
case Byte b -> String.format(“byte %d", b);
case Long l -> String.format(“long %d", l);
case Double d -> String.format(“double %f", d);
case String s -> String.format("String %s", s);
// Short, Character, Float, Boolean
default -> "unknown";
};
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.9
Generalizing Switch: Constant Patterns
String s =
exprswitch (num) {
case 0 -> "zero";
case 1 -> "one";
case int i -> "some other Integer";
default -> "not an Integer";
};
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.10
Destructuring Patterns
if (node matches AddNode(Node x, Node y)) { ... }
int eval(Node n) {
return exprswitch(n) {
case IntNode(int i) -> i;
case NegNode(Node n) -> -eval(n);
case AddNode(Node left, Node right) -> eval(left) + eval(right);
case MulNode(Node left, Node right) -> eval(left) * eval(right);
};
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.11
Nested Patterns
if (node matches AddNode(Node x, Node y)) { ... }
- “Node x” may look like binding variable declaration
- It is actually a nested type test pattern !
The pattern AddNode(p1, p2), where p1 and p2 are patterns, matches a target if:
- the target is an AddNode;
- the left component of that AddNode matches p1;
- the right component of that AddNode matches p2.
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.12
Evaluating Expressions: Var patterns
int eval(Node n) {
return switch(n) {
case IntNode(var i) -> i;
case NegNode(var n) -> -eval(n);
case AddNode(var left, var right) -> eval(left) + eval(right);
case MulNode(var left, var right) -> eval(left) * eval(right);
case ParenNode(var node) -> eval(node);
};
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.13
Nesting Constant patterns
String formatted = exprswitch (anObject) {
case Point(0, 0) -> "at origin";
case Point(0, var y) -> "on x axis";
case Point(var x, 0) -> "on y axis";
case Point(var x, var y) -> String.format("[%d,%d]", x, y);
default -> "not a point";
};
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.14
Example: Simplifying Expressions
 Suppose we want to simplify algebraic expressions
– 0 + e == e
– 1 * e == e
– 0 * e == 0
– etc
 We could do this with Visitors … yuck
– Much easier with pattern matching
– Less ceremony, easier composition
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.15
Nesting nontrivial patterns
Node simplify(Node n) {
return switch(n) {
case IntNode -> n;
case NegNode(NegNode(var n)) -> simplify(n);
case NegNode(var n) -> simplify(new NegNode(simplify(n)));
case AddNode(IntNode(0), var right) -> simplify(right);
case AddNode(var left, IntNode(0)) -> simplify(left);
case AddNode(var left, var right)
-> simplify(new AddNode(simplify(left), simplify(right)));
case MulNode(IntNode(1), var right) -> simplify(right);
case MulNode(var left, IntNode(1)) -> simplify(left);
case MulNode(IntNode(0), var right) -> new IntNode(0);
case MulNode(var left, IntNode(0)) -> new IntNode(0);
case MulNode(var left, var right)
-> simplify(new MulNode(simplify(left), simplify(right)));
};
}
Node simplify(Node n) {
return switch(n) {
case IntNode -> n;
case NegNode(NegNode(var n)) -> simplify(n);
case NegNode(var n) -> simplify(new NegNode(simplify(n)));
case AddNode(IntNode(0), var right) -> simplify(right);
case AddNode(var left, IntNode(0)) -> simplify(left);
case AddNode(var left, var right)
-> simplify(new AddNode(simplify(left), simplify(right)));
case MulNode(IntNode(1), var right) -> simplify(right);
case MulNode(var left, IntNode(1)) -> simplify(left);
case MulNode(IntNode(0), var right) -> new IntNode(0);
case MulNode(var left, IntNode(0)) -> new IntNode(0);
case MulNode(var left, var right)
-> simplify(new MulNode(simplify(left), simplify(right)));
};
}
Nested Pattern!
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.16
The _ pattern
case MulNode(IntNode(0), _) -> new IntNode(0);
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.17
Patterns - Summary
Types of Patterns:
- Type-test patterns, which bind the cast target to a binding variable;
- Destructuring patterns, which destructure the target and recursively match
- Constant patterns, which match on equality;
- Var patterns, which match anything and bind their target;
- The _ pattern, which matches anything.
Contexts:
- Matches predicate
- Enhanced switch statement
- Expression switch
Pattern Matching in Java - Srikanth Sankaran

Weitere ähnliche Inhalte

Was ist angesagt?

7. Rest parameters | ES6 | JavaScript
7. Rest parameters | ES6 | JavaScript7. Rest parameters | ES6 | JavaScript
7. Rest parameters | ES6 | JavaScriptpcnmtutorials
 
Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Hariz Mustafa
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVMJarek Ratajski
 
20171127 當julia遇上資料科學
20171127 當julia遇上資料科學20171127 當julia遇上資料科學
20171127 當julia遇上資料科學岳華 杜
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingHariz Mustafa
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8Roland Mast
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia岳華 杜
 

Was ist angesagt? (16)

7. Rest parameters | ES6 | JavaScript
7. Rest parameters | ES6 | JavaScript7. Rest parameters | ES6 | JavaScript
7. Rest parameters | ES6 | JavaScript
 
Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3
 
Abaqus_hdf5_interOp
Abaqus_hdf5_interOpAbaqus_hdf5_interOp
Abaqus_hdf5_interOp
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVM
 
20171127 當julia遇上資料科學
20171127 當julia遇上資料科學20171127 當julia遇上資料科學
20171127 當julia遇上資料科學
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handling
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia
 
Java generics final
Java generics finalJava generics final
Java generics final
 
JavaYDL6
JavaYDL6JavaYDL6
JavaYDL6
 
Java Beagle
Java BeagleJava Beagle
Java Beagle
 
Array&string
Array&stringArray&string
Array&string
 
Trie Data Structure
Trie Data StructureTrie Data Structure
Trie Data Structure
 
Trie Data Structure
Trie Data StructureTrie Data Structure
Trie Data Structure
 
SOLID Java Code
SOLID Java CodeSOLID Java Code
SOLID Java Code
 

Ähnlich wie Pattern Matching in Java - Srikanth Sankaran

JCConf 2021 - Java17: The Next LTS
JCConf 2021 - Java17: The Next LTSJCConf 2021 - Java17: The Next LTS
JCConf 2021 - Java17: The Next LTSJoseph Kuo
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
IntroductiontoprogramminginscalaAmuhinda Hungai
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvmIsaias Barroso
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascriptMD Sayem Ahmed
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 
An introduction to Raku
An introduction to RakuAn introduction to Raku
An introduction to RakuSimon Proctor
 
Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...
Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...
Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...Holden Karau
 
Read carefully. Im not sure if the point class is correct but postin.pdf
Read carefully. Im not sure if the point class is correct but postin.pdfRead carefully. Im not sure if the point class is correct but postin.pdf
Read carefully. Im not sure if the point class is correct but postin.pdfbharatchawla141
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
Data weave 2.0 advanced (recursion, pattern matching)
Data weave 2.0   advanced (recursion, pattern matching)Data weave 2.0   advanced (recursion, pattern matching)
Data weave 2.0 advanced (recursion, pattern matching)ManjuKumara GH
 
Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"Gouda Mando
 

Ähnlich wie Pattern Matching in Java - Srikanth Sankaran (20)

JCConf 2021 - Java17: The Next LTS
JCConf 2021 - Java17: The Next LTSJCConf 2021 - Java17: The Next LTS
JCConf 2021 - Java17: The Next LTS
 
Java script summary
Java script summaryJava script summary
Java script summary
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Scala.js
Scala.jsScala.js
Scala.js
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
 
Text processing by Rj
Text processing by RjText processing by Rj
Text processing by Rj
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
An introduction to Raku
An introduction to RakuAn introduction to Raku
An introduction to Raku
 
Java Annotations and Pre-processing
Java  Annotations and Pre-processingJava  Annotations and Pre-processing
Java Annotations and Pre-processing
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...
Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...
Beyond Shuffling, Tips and Tricks for Scaling Apache Spark updated for Spark ...
 
Read carefully. Im not sure if the point class is correct but postin.pdf
Read carefully. Im not sure if the point class is correct but postin.pdfRead carefully. Im not sure if the point class is correct but postin.pdf
Read carefully. Im not sure if the point class is correct but postin.pdf
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Data weave 2.0 advanced (recursion, pattern matching)
Data weave 2.0   advanced (recursion, pattern matching)Data weave 2.0   advanced (recursion, pattern matching)
Data weave 2.0 advanced (recursion, pattern matching)
 
Java
JavaJava
Java
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"
 

Mehr von Eclipse Day India

Java Performance Testing for Everyone - Shelley Lambert
Java Performance Testing for Everyone - Shelley LambertJava Performance Testing for Everyone - Shelley Lambert
Java Performance Testing for Everyone - Shelley LambertEclipse Day India
 
Eclipse IDE Tips and Tricks - Lakshmi Priya Shanmugam
Eclipse IDE Tips and Tricks - Lakshmi Priya ShanmugamEclipse IDE Tips and Tricks - Lakshmi Priya Shanmugam
Eclipse IDE Tips and Tricks - Lakshmi Priya ShanmugamEclipse Day India
 
Machine Learning for Java Developers - Nasser Ebrahim
Machine Learning for Java Developers - Nasser EbrahimMachine Learning for Java Developers - Nasser Ebrahim
Machine Learning for Java Developers - Nasser EbrahimEclipse Day India
 
Scaling Eclipse on HiDPI Monitors - Niraj Modi
Scaling Eclipse on HiDPI Monitors - Niraj ModiScaling Eclipse on HiDPI Monitors - Niraj Modi
Scaling Eclipse on HiDPI Monitors - Niraj ModiEclipse Day India
 
Please Behave Yourself: BDD and automating Eclipse RCP applications using JBe...
Please Behave Yourself: BDD and automating Eclipse RCP applications using JBe...Please Behave Yourself: BDD and automating Eclipse RCP applications using JBe...
Please Behave Yourself: BDD and automating Eclipse RCP applications using JBe...Eclipse Day India
 
Supporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
Supporting Java™ 9 in Eclipse - A critical perspective - Stephan HerrmannSupporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
Supporting Java™ 9 in Eclipse - A critical perspective - Stephan HerrmannEclipse Day India
 
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jerseyEclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jerseyEclipse Day India
 
Eclipse Day India 2015 - Java bytecode analysis and JIT
Eclipse Day India 2015 - Java bytecode analysis and JITEclipse Day India 2015 - Java bytecode analysis and JIT
Eclipse Day India 2015 - Java bytecode analysis and JITEclipse Day India
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India
 
Eclipse Day India 2015 - Java 9
Eclipse Day India 2015 - Java 9Eclipse Day India 2015 - Java 9
Eclipse Day India 2015 - Java 9Eclipse Day India
 
Eclipse Day India 2015 - Keynote - Stephan Herrmann
Eclipse Day India 2015 - Keynote - Stephan HerrmannEclipse Day India 2015 - Keynote - Stephan Herrmann
Eclipse Day India 2015 - Keynote - Stephan HerrmannEclipse Day India
 
Eclipse Day India 2015 - Eclipse RCP testing using Jubula based automation
Eclipse Day India 2015 - Eclipse RCP testing using Jubula based automationEclipse Day India 2015 - Eclipse RCP testing using Jubula based automation
Eclipse Day India 2015 - Eclipse RCP testing using Jubula based automationEclipse Day India
 
Eclipse Day India 2015 - Oomph
Eclipse Day India 2015 - OomphEclipse Day India 2015 - Oomph
Eclipse Day India 2015 - OomphEclipse Day India
 
Eclipse Day India 2015 - Keynote (Mike Milinkovich)
Eclipse Day India 2015 - Keynote (Mike Milinkovich)Eclipse Day India 2015 - Keynote (Mike Milinkovich)
Eclipse Day India 2015 - Keynote (Mike Milinkovich)Eclipse Day India
 
Eclipse Day India 2015 - Unleashing the Java 8 Tooling in Eclipse
Eclipse Day India 2015 - Unleashing the Java 8 Tooling in EclipseEclipse Day India 2015 - Unleashing the Java 8 Tooling in Eclipse
Eclipse Day India 2015 - Unleashing the Java 8 Tooling in EclipseEclipse Day India
 

Mehr von Eclipse Day India (20)

Java Performance Testing for Everyone - Shelley Lambert
Java Performance Testing for Everyone - Shelley LambertJava Performance Testing for Everyone - Shelley Lambert
Java Performance Testing for Everyone - Shelley Lambert
 
Eclipse IDE Tips and Tricks - Lakshmi Priya Shanmugam
Eclipse IDE Tips and Tricks - Lakshmi Priya ShanmugamEclipse IDE Tips and Tricks - Lakshmi Priya Shanmugam
Eclipse IDE Tips and Tricks - Lakshmi Priya Shanmugam
 
Machine Learning for Java Developers - Nasser Ebrahim
Machine Learning for Java Developers - Nasser EbrahimMachine Learning for Java Developers - Nasser Ebrahim
Machine Learning for Java Developers - Nasser Ebrahim
 
Scaling Eclipse on HiDPI Monitors - Niraj Modi
Scaling Eclipse on HiDPI Monitors - Niraj ModiScaling Eclipse on HiDPI Monitors - Niraj Modi
Scaling Eclipse on HiDPI Monitors - Niraj Modi
 
Please Behave Yourself: BDD and automating Eclipse RCP applications using JBe...
Please Behave Yourself: BDD and automating Eclipse RCP applications using JBe...Please Behave Yourself: BDD and automating Eclipse RCP applications using JBe...
Please Behave Yourself: BDD and automating Eclipse RCP applications using JBe...
 
Supporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
Supporting Java™ 9 in Eclipse - A critical perspective - Stephan HerrmannSupporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
Supporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
 
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jerseyEclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
 
Eclipse Day India 2015 - Java bytecode analysis and JIT
Eclipse Day India 2015 - Java bytecode analysis and JITEclipse Day India 2015 - Java bytecode analysis and JIT
Eclipse Day India 2015 - Java bytecode analysis and JIT
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
 
Eclipse Day India 2015 - Java 9
Eclipse Day India 2015 - Java 9Eclipse Day India 2015 - Java 9
Eclipse Day India 2015 - Java 9
 
Eclipse Day India 2015 - Keynote - Stephan Herrmann
Eclipse Day India 2015 - Keynote - Stephan HerrmannEclipse Day India 2015 - Keynote - Stephan Herrmann
Eclipse Day India 2015 - Keynote - Stephan Herrmann
 
Eclipse Day India 2015 - Eclipse RCP testing using Jubula based automation
Eclipse Day India 2015 - Eclipse RCP testing using Jubula based automationEclipse Day India 2015 - Eclipse RCP testing using Jubula based automation
Eclipse Day India 2015 - Eclipse RCP testing using Jubula based automation
 
Eclipse Day India 2015 - Oomph
Eclipse Day India 2015 - OomphEclipse Day India 2015 - Oomph
Eclipse Day India 2015 - Oomph
 
Eclipse Day India 2015 - Keynote (Mike Milinkovich)
Eclipse Day India 2015 - Keynote (Mike Milinkovich)Eclipse Day India 2015 - Keynote (Mike Milinkovich)
Eclipse Day India 2015 - Keynote (Mike Milinkovich)
 
Eclipse Day India 2015 - Unleashing the Java 8 Tooling in Eclipse
Eclipse Day India 2015 - Unleashing the Java 8 Tooling in EclipseEclipse Day India 2015 - Unleashing the Java 8 Tooling in Eclipse
Eclipse Day India 2015 - Unleashing the Java 8 Tooling in Eclipse
 
IDS and Bluemix
IDS and BluemixIDS and Bluemix
IDS and Bluemix
 
SWT - Technical Deep Dive
SWT - Technical Deep DiveSWT - Technical Deep Dive
SWT - Technical Deep Dive
 
PDE builds or Maven
PDE builds or MavenPDE builds or Maven
PDE builds or Maven
 
Orion - IDE on the cloud
Orion - IDE on the cloudOrion - IDE on the cloud
Orion - IDE on the cloud
 
KlighD
KlighDKlighD
KlighD
 

Kürzlich hochgeladen

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 

Kürzlich hochgeladen (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Pattern Matching in Java - Srikanth Sankaran

  • 1. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.1 Pattern Matching in Java Srikanth Sankaran, Consulting Member of Technical Staff Java Product Group, Oracle August 2017
  • 2. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.2 The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.
  • 3. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.3 Pattern Matching - Motivation if (obj instanceof Integer) { int intValue = ((Integer) obj).intValue(); // use intValue }  Test to see if an expression has some characteristic  Convert  Destructure and extract interesting state bits
  • 4. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.4 Pattern Matching - Motivation String formatted = "unknown"; if (obj instanceof Integer) { int i = (Integer) obj; formatted = String.format("int %d", i); } else if (obj instanceof Byte) { byte b = (Byte) obj; formatted = String.format("byte %d", b); } else if (obj instanceof Long) { long l = (Long) obj; formatted = String.format("long %d", l); } else if (obj instanceof Double) { double d = (Double) obj; formatted = String.format(“double %f", d); } else if (obj instanceof String) { String s = (String) obj; formatted = String.format("String %s", s); } // ...
  • 5. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.5 Pattern Matching – Type Test Patterns  Pattern – A combination of a predicate applied to a target & – A set of binding variables extracted from the target if predicate applies to it. if (x matches Integer i) { // can use i here }
  • 6. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.6 Pattern Matching – Type Test Patterns String formatted = "unknown"; if (obj matches Integer i) { formatted = String.format("int %d", i); } else if (obj matches Byte b) { formatted = String.format("byte %d", b); } else if (obj matches Long l) { formatted = String.format("long %d", l); } else if (obj matches Double d) { formatted = String.format(“double %f", d); } else if (obj matches String s) { formatted = String.format("String %s", s); } // ...
  • 7. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.7 Improved Switch String formatted; switch (constant) { case Integer i: formatted = String.format("int %d", i); break; case Byte b: formatted = String.format(“byte %d",b); break; case Long l: formatted = String.format(“long %d",l); break; case Double d: formatted = String.format(“double %f", d); break; // String, Short, Character, Float, Boolean default: formatted = "unknown"; }
  • 8. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.8 Expression Switch String formatted = switch (constant) { case Integer i -> String.format("int %d", i); case Byte b -> String.format(“byte %d", b); case Long l -> String.format(“long %d", l); case Double d -> String.format(“double %f", d); case String s -> String.format("String %s", s); // Short, Character, Float, Boolean default -> "unknown"; };
  • 9. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.9 Generalizing Switch: Constant Patterns String s = exprswitch (num) { case 0 -> "zero"; case 1 -> "one"; case int i -> "some other Integer"; default -> "not an Integer"; };
  • 10. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.10 Destructuring Patterns if (node matches AddNode(Node x, Node y)) { ... } int eval(Node n) { return exprswitch(n) { case IntNode(int i) -> i; case NegNode(Node n) -> -eval(n); case AddNode(Node left, Node right) -> eval(left) + eval(right); case MulNode(Node left, Node right) -> eval(left) * eval(right); }; }
  • 11. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.11 Nested Patterns if (node matches AddNode(Node x, Node y)) { ... } - “Node x” may look like binding variable declaration - It is actually a nested type test pattern ! The pattern AddNode(p1, p2), where p1 and p2 are patterns, matches a target if: - the target is an AddNode; - the left component of that AddNode matches p1; - the right component of that AddNode matches p2.
  • 12. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.12 Evaluating Expressions: Var patterns int eval(Node n) { return switch(n) { case IntNode(var i) -> i; case NegNode(var n) -> -eval(n); case AddNode(var left, var right) -> eval(left) + eval(right); case MulNode(var left, var right) -> eval(left) * eval(right); case ParenNode(var node) -> eval(node); }; }
  • 13. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.13 Nesting Constant patterns String formatted = exprswitch (anObject) { case Point(0, 0) -> "at origin"; case Point(0, var y) -> "on x axis"; case Point(var x, 0) -> "on y axis"; case Point(var x, var y) -> String.format("[%d,%d]", x, y); default -> "not a point"; };
  • 14. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.14 Example: Simplifying Expressions  Suppose we want to simplify algebraic expressions – 0 + e == e – 1 * e == e – 0 * e == 0 – etc  We could do this with Visitors … yuck – Much easier with pattern matching – Less ceremony, easier composition
  • 15. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.15 Nesting nontrivial patterns Node simplify(Node n) { return switch(n) { case IntNode -> n; case NegNode(NegNode(var n)) -> simplify(n); case NegNode(var n) -> simplify(new NegNode(simplify(n))); case AddNode(IntNode(0), var right) -> simplify(right); case AddNode(var left, IntNode(0)) -> simplify(left); case AddNode(var left, var right) -> simplify(new AddNode(simplify(left), simplify(right))); case MulNode(IntNode(1), var right) -> simplify(right); case MulNode(var left, IntNode(1)) -> simplify(left); case MulNode(IntNode(0), var right) -> new IntNode(0); case MulNode(var left, IntNode(0)) -> new IntNode(0); case MulNode(var left, var right) -> simplify(new MulNode(simplify(left), simplify(right))); }; } Node simplify(Node n) { return switch(n) { case IntNode -> n; case NegNode(NegNode(var n)) -> simplify(n); case NegNode(var n) -> simplify(new NegNode(simplify(n))); case AddNode(IntNode(0), var right) -> simplify(right); case AddNode(var left, IntNode(0)) -> simplify(left); case AddNode(var left, var right) -> simplify(new AddNode(simplify(left), simplify(right))); case MulNode(IntNode(1), var right) -> simplify(right); case MulNode(var left, IntNode(1)) -> simplify(left); case MulNode(IntNode(0), var right) -> new IntNode(0); case MulNode(var left, IntNode(0)) -> new IntNode(0); case MulNode(var left, var right) -> simplify(new MulNode(simplify(left), simplify(right))); }; } Nested Pattern!
  • 16. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.16 The _ pattern case MulNode(IntNode(0), _) -> new IntNode(0);
  • 17. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.17 Patterns - Summary Types of Patterns: - Type-test patterns, which bind the cast target to a binding variable; - Destructuring patterns, which destructure the target and recursively match - Constant patterns, which match on equality; - Var patterns, which match anything and bind their target; - The _ pattern, which matches anything. Contexts: - Matches predicate - Enhanced switch statement - Expression switch