Pattern Matching パターンマッチング
パターン マッチングでは、オブジェクトが特定の構造を持っているかどうかをテストし、一致する場合はそのオブジェクトからデータを抽出します。Java ではすでにこれを行うことができます。ただし、パターン マッチングでは、より簡潔で堅牢なコードを使用してオブジェクトから条件付きでデータを抽出できるようにする新しい言語拡張機能が導入されています。
Pattern Matching for the instanceof Operator
- 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.
Pattern Matchingの実装
public class Main {
public static void main(String[] args) {
Shape rec = new Rectangle(2.0,4.0);
System.out.println("rec:"+getPerimeter(rec));
Shape cir = new Circle(2.0);
System.out.println("cir:"+getPerimeter(cir));
}
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");
}
}
}
interface Shape { }
record Rectangle(double length, double width) implements Shape { }
record Circle(double radius) implements Shape { }
Pattern Matchingの実行結果
C:\sctree\sample\test-v17\out\production\test-v17 Main
rec:12.0
cir:12.566370614359172
Process finished with exit code 0