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
Eric McIntyre
Eric McIntyre15mo ago
Java's instanceof operator allows checking whether an object can be cast to a certain type:
Object stringAsObject = "Hello World";
System.out.println(stringAsObject instanceof String);//true
System.out.println(stringAsObject instanceof LocalDate);//false
Object stringAsObject = "Hello World";
System.out.println(stringAsObject instanceof String);//true
System.out.println(stringAsObject instanceof LocalDate);//false
This is often used together with a cast. After checking the type of the object, one can cast the object to the type:
Object o = getSomeObject();
if (o instanceof String){
//here, we know that o is a String so we can cast o to a String
String s = (String) o;
System.out.println("We have a String of length "+s.length());
}
Object o = getSomeObject();
if (o instanceof String){
//here, we know that o is a String so we can cast o to a String
String s = (String) o;
System.out.println("We have a String of length "+s.length());
}
Since Java 16, the above code can be simplified to do the instanceof check and the cast in one step:
Object o = getSomeObject();
if (o instanceof String s){//checks whether o is a String, casts it to String and assigns it to a new String variable named s
System.out.println("We have a String of length "+s.length());
}
//System.out.println("We have a String of length "+s.length());//compile-time error since variable is out of scope
Object o = getSomeObject();
if (o instanceof String s){//checks whether o is a String, casts it to String and assigns it to a new String variable named s
System.out.println("We have a String of length "+s.length());
}
//System.out.println("We have a String of length "+s.length());//compile-time error since variable is out of scope
📖 Sample answer from dan1st
Eric McIntyre
Eric McIntyre15mo ago
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
Want results from more Discord servers?
Add your server