99. Tackling guarded record patterns
Exactly as in the case of type patterns, we can add guarding conditions based on the binding variables. For instance, the following code uses guarding conditions with instanceof
for determining if the Allergy cabinet is open or closed (you should be familiar with the Doctor
record from the previous two problems):
public static String cabinet(Staff staff) {
if (staff instanceof Doctor(String name, String specialty)
&& (specialty.equals("Allergy")
&& (name.equals("Kyle Ulm")))) {
return "The cabinet of " + specialty
+ " is closed. The doctor "
+ name + " is on holiday.";
}
if (staff instanceof Doctor(String name, String specialty)
&& (specialty.equals("Allergy")
&& (name.equals("John Hora")))) {
return "The cabinet of " + specialty
+ " is open...