public static double getPerimeter(Shape shape) throws IllegalArgumentException {
if (shape instanceof Rectangle r) {
return 2 * r.length() + 2 * r.width();
} else if (shape instanceof Circle c) {
return 2 * c.radius() * Math.PI;
} else {
throw new IllegalArgumentException("Unrecognized shape");
}
}
I'm currently reading the docs for the pattern matching expression. In the docs, part of it says this:
A pattern is a combination of a test, which is called a predicate; a target; and a set of local variables, which are called pattern variables:
The predicate is a Boolean-valued function with one argument; in this case, it’s the instanceof operator testing whether the Shape argument is a Rectangle or a Circle.
The target is the argument of the predicate, which is the Shape value.
The pattern variables are those that store data from the target only if the predicate returns true, which are the variables r and s.
Can someone explain the third part where the we talk about pattern variables pls. So if it's an instance of Rectangle for e.g, we create a variable named r of type Rectangle?