98. Introducing record patterns for switch
You already know that type patterns can be used for instanceof
and switch
expressions. This statement is true for record patterns as well. For instance, let’s reiterate the Doctor
and Resident
records:
public record Doctor(String name, String specialty)
implements Staff {}
public record Resident(String name, Doctor doctor)
implements Staff {}
We can easily use these two records via record patterns in a switch
expression as follows:
public static String cabinet(Staff staff) {
return switch(staff) {
case Doctor(var name, var specialty)
-> "Cabinet of " + specialty + ". Doctor: " + name;
case Resident(var rsname, Doctor(var drname, var specialty))
-> "Cabinet of " + specialty + ". Doctor: "
+ drname + ", Resident: " + rsname;
default -> "Cabinet closed";
};
}
Adding more nested records follows the same...