Pattern Matching for instanceof
Bind a variable while testing type.
Pattern Matching for instanceof
The old way to use instanceof was test-then-cast. Pattern matching combines the test and the cast into one step, binding a typed variable when the test passes.
The Old Boilerplate
Classic code checks the type, then casts to a new variable. It is repetitive and easy to get wrong.
public class Main {
public static void main(String[] args) {
Object obj = "hello";
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}
}
}All lessons in this course
- Pattern Matching for instanceof
- Record Patterns
- Nested Record Patterns
- Patterns in switch