SlideShare a Scribd company logo
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

More Related Content

What's hot

7. Rest parameters | ES6 | JavaScript
7. Rest parameters | ES6 | JavaScript7. Rest parameters | ES6 | JavaScript
7. Rest parameters | ES6 | JavaScript
pcnmtutorials
 
Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3
Hariz Mustafa
 
Abaqus_hdf5_interOp
Abaqus_hdf5_interOpAbaqus_hdf5_interOp
Abaqus_hdf5_interOp
Anshuman Singh
 
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
Jarek 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_handling
Hariz Mustafa
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8
Roland Mast
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
sholavanalli
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia
岳華 杜
 
Java generics final
Java generics finalJava generics final
Java generics final
Akshay Chaudhari
 
JavaYDL6
JavaYDL6JavaYDL6
JavaYDL6
Terry Yoast
 
Java Beagle
Java BeagleJava Beagle
Java Beagle
adil raja
 
Array&string
Array&stringArray&string
Array&string
chanchal ghosh
 
Trie Data Structure
Trie Data StructureTrie Data Structure
Trie Data Structure
Badiuzzaman Pranto
 
Trie Data Structure
Trie Data StructureTrie Data Structure
SOLID Java Code
SOLID Java CodeSOLID Java Code
SOLID Java Code
Omar Bashir
 

What's hot (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
 

Similar to 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 LTS
Joseph Kuo
 
Java script summary
Java script summaryJava script summary
Java script summary
maamir farooq
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
Amuhinda 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 jvm
Isaias Barroso
 
Scala.js
Scala.jsScala.js
Scala.js
Vitaly Tsaplin
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
MD Sayem Ahmed
 
Text processing by Rj
Text processing by RjText 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
Keshav 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 programming
Keshav Kumar
 
An introduction to Raku
An introduction to RakuAn introduction to Raku
An introduction to Raku
Simon Proctor
 
Java Annotations and Pre-processing
Java  Annotations and Pre-processingJava  Annotations and Pre-processing
Java Annotations and Pre-processing
Danilo Pereira De Luca
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
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.pdf
bharatchawla141
 
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
Miles Sabin
 
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
Miles 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
JavaJava
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
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
 

Similar to 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
 
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
 
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
 
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"
 

More from 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 Lambert
Eclipse 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 Shanmugam
Eclipse 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 Ebrahim
Eclipse 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 Modi
Eclipse 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 Herrmann
Eclipse 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 jersey
Eclipse 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 JIT
Eclipse 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 Overview
Eclipse Day India
 
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
 
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
 
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
 
Eclipse Day India 2015 - Oomph
Eclipse Day India 2015 - OomphEclipse Day India 2015 - Oomph
Eclipse Day India 2015 - Oomph
Eclipse 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 Eclipse
Eclipse Day India
 
IDS and Bluemix
IDS and BluemixIDS and Bluemix
IDS and Bluemix
Eclipse Day India
 
SWT - Technical Deep Dive
SWT - Technical Deep DiveSWT - Technical Deep Dive
SWT - Technical Deep Dive
Eclipse Day India
 
PDE builds or Maven
PDE builds or MavenPDE builds or Maven
PDE builds or Maven
Eclipse Day India
 
Orion - IDE on the cloud
Orion - IDE on the cloudOrion - IDE on the cloud
Orion - IDE on the cloud
Eclipse Day India
 
KlighD
KlighDKlighD

More from 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
 

Recently uploaded

A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 

Recently uploaded (20)

A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 

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