Skip to content

Commit bbb0fe5

Browse files
cushonError Prone Team
authored and
Error Prone Team
committed
Add an explanation for PatternMatchingInstanceof
PiperOrigin-RevId: 736288615
1 parent f439f9c commit bbb0fe5

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
Pattern matching with `instanceof` allows writing this:
2+
3+
```java
4+
void handle(Object o) {
5+
if (o instanceof Point(int x, int y)) {
6+
handlePoint(x, y);
7+
} else if (o instanceof String s) {
8+
handleString(s);
9+
}
10+
}
11+
```
12+
13+
which is more concise than an instanceof and a separate cast:
14+
15+
```java
16+
void handle(Object o) {
17+
if (o instanceof Point) {
18+
Point point = (Point) o;
19+
handlePoint(point.x(), point.y());
20+
} else if (o instanceof String) {
21+
String s = (String) o;
22+
handleString(s);
23+
}
24+
}
25+
```
26+
27+
For more information on pattern matching and `instanceof`, see
28+
[Pattern Matching for the instanceof Operator](https://docs.oracle.com/en/java/javase/21/language/pattern-matching-instanceof.html)

0 commit comments

Comments
 (0)