Skip to content

Commit 13ca9d8

Browse files
committed
JDK 21: update example of pattern matching for switch
1 parent 44578ef commit 13ca9d8

2 files changed

Lines changed: 94 additions & 1 deletion

File tree

java-21/PatternMatchingForSwitchTest.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ public class PatternMatchingForSwitchTest {
44
public static void main(String[] args) {
55
switchExhaustivenessAndCompatibility();
66
switchExpressionWithPatternMatching();
7+
switchScopeWithPatternMatching();
78
switchEnhancedTypeChecking();
89
switchWithGuardedCaseLabel();
910
switchWithEnumConstants();
@@ -26,6 +27,17 @@ static void switchExhaustivenessAndCompatibility() {
2627
}
2728

2829
var shape = Shape.TRIANGLE;
30+
// default case way
31+
switch (shape) {
32+
case TRIANGLE:
33+
System.out.println("Is a triangle");
34+
break;
35+
case CIRCLE:
36+
System.out.println("Is a circle");
37+
break;
38+
}
39+
40+
// lambda expression way
2941
switch (shape) {
3042
case TRIANGLE -> System.out.println("Is a triangle");
3143
case CIRCLE -> System.out.println("Is a circle");
@@ -51,6 +63,48 @@ static void switchExpressionWithPatternMatching() {
5163
System.out.println(message);
5264
}
5365

66+
static void switchScopeWithPatternMatching() {
67+
Number number = 42;
68+
69+
String message = null;
70+
71+
switch (number) {
72+
case Integer i when i == 0:
73+
System.out.println("zero =0");
74+
// doesn't allow fall-through (must have the break or yield when using `:` in a switch statement or expression)
75+
// error: illegal fall-through to a pattern
76+
break;
77+
78+
case Integer x when x < 0:
79+
message = "zero or lower";
80+
break;
81+
case Integer n when n == 21:
82+
message = "half of the answer";
83+
break;
84+
case Integer n when n == 42:
85+
message = "answer";
86+
break;
87+
default:
88+
message = "unhandled";
89+
}
90+
System.out.println("switch statement: " + message);
91+
92+
message = switch (number) {
93+
case Integer i when i == 0:
94+
System.out.println("zero =0");
95+
yield "zero =0";
96+
case Integer x when x < 0:
97+
yield "zero or lower";
98+
case Integer n when n == 21:
99+
yield "half of the answer";
100+
case Integer n when n == 42:
101+
yield "answer";
102+
default:
103+
yield "unhandled";
104+
};
105+
System.out.println("switch expression: " + message);
106+
}
107+
54108
static void switchEnhancedTypeChecking() {
55109
Object value = 42;
56110
var message = switch (value) {
@@ -102,6 +156,7 @@ static void switchWithEnumConstants() {
102156
case Shape.CIRCLE -> "Circle";
103157
case Shape.RECTANGLE -> "Rectangle";
104158
case Shape.TRIANGLE -> "Triangle";
159+
default -> "other type";
105160
};
106161
System.out.println(shapeName);
107162
}

java-21/README.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,28 @@ To run each example use: `java --enable-preview --source 21 <FileName.java>`
2020
## Features
2121

2222
* Virtual threads
23+
* promotion to standard
2324
* changed to make virtual threads always support thread-local
2425
* in preview releases was possible to create a virtual thread without thread-local support
2526
* flag `jdk.traceVirtualThreadLocals` to show the strack trace when a virtual threads sets a value in thread-local variable
2627
* Record patterns
28+
* promotion to standard
2729
* the main change is remove the support for record pattern in header of an enhanced for loop
2830
* Pattern matching for `switch`
31+
* promotion to standard
2932
* main changes from last JEPs:
3033
* removed parenthesized patterns (`case int i when (i > 0)`)
31-
* allow qualified enum constants as case constants
34+
* allow qualified enum constants as case constants (`case MyEnum.ITEM`)
3235
* exhaustiveness and compatibility:
3336
* compiler will only require exhaustiveness if the switch uses any pattern, null label or if selector expression isn't from a legacy type (char, byte, short, int, Character, Byte, Short, Integer, String or a enum)
37+
* improved switch to support pattern matching for types (like `instanceof`)
38+
* support for `null` case
39+
* support for guards where we can use a boolean expression (`case String s when s.length > 10`)
40+
* scope for pattern variable:
41+
* the scope of pattern variable in visible only in the guard clause and the case body (expression, block or throw)
42+
* fall through:
43+
* `switch` with type pattern doesn't support falling through
44+
* if using case label with `:`, we must end the block with `break` or `yield` (`case String s: ...; break;`, `case String s: ...; yield s.length();`)
3445
* String templates:
3546
* improve the string with embedded expressions and template processors
3647
* goals:
@@ -106,6 +117,7 @@ To run each example use: `java --enable-preview --source 21 <FileName.java>`
106117
* `unmodifiableSequencedSet`
107118
* `unmodifiableSequencedMap`
108119
* Unnamed classes and instance main methods
120+
* a.k.a. relaxed launch protocol
109121
* facilitate the writing of first programm for students without needing to know another features designed for large programs
110122
* unnamed class:
111123
* any method declared in a source file without an enclosed class will be considered to be member of an unnamed top-level class
@@ -149,6 +161,32 @@ To run each example use: `java --enable-preview --source 21 <FileName.java>`
149161
* `static void main()`
150162
* `void main(String[])`
151163
* `void main()`
164+
* Unnamed patterns and variables
165+
* goals:
166+
* improve the readability of record patterns by ediling unnecessary nested patterns
167+
* improve the maintanability of code by identifying variables that must be declared but will not be used
168+
* unnamed pattern is denoted by `_`
169+
* it is a shorthand for the type pattern `var _`
170+
* it will facilitate the pattern matching where we are interested in the data types or structure
171+
* unnamed variables:
172+
* it never shadows another variable, can be used many times
173+
* it can be used when:
174+
* declaring a local variable (`int _ = q.remove()`)
175+
* resource specification of a try-with-resources (`try (_ = ScopedContxt.acquire())`)
176+
* exception parameter in a catch clause (`catch (NumberFormatException _)`)
177+
* header of an enhanced for loop (`for (int i = 0; _ = sideEffect(); i++)`)
178+
* header of an enhanced for loop (`for (Order _ : orders)`)
179+
* lambda parameter (`(int x, int _) -> x + x`, `_ -> "lambda with single parameter"`)
180+
* unnamed patterns:
181+
* unnamed pattern is an unconditional pattern which binds nothing
182+
* we can use it in a nested position of a type pattern or a record pattern
183+
* `p instanceof Point(_, int y)`
184+
* `case Point(int x, _)`
185+
* `p instanceof ColoredPoint(Point _, Color c)`
186+
* unnamed pattern variables:
187+
* we can use it in any type pattern
188+
* `p instanceof Point _`
189+
* `case Point _`
152190
* APIs:
153191
* improve `Thread.sleep(millis, nanos)` to actually perform sleep with sub-millisecond time
154192
* [`java.net.http.Http Client` is now `AutoCloseable`](https://jdk.java.net/21/release-notes#JDK-8267140) and new methods were added to close/shutdown the connection pool.

0 commit comments

Comments
 (0)