Week 40 — What is instanceof patternmatching and how can it be used?
Question of the Week #40
What is instanceof patternmatching and how can it be used?
2 Replies
Java's
instanceof
operator allows checking whether an object can be cast to a certain type:
This is often used together with a cast. After checking the type of the object, one can cast the object to the type:
Since Java 16, the above code can be simplified to do the instanceof
check and the cast in one step:
📖 Sample answer from dan1st
To make a parse without need to do it in two steps, and avoid need to error handling.
If (brazilian instanceof Person person) {
System.out.println("Olá pessoal by "+ person.gerName());
}
Submission from fabriciogscarvalho