record Click(int x, int y) implements UserAction {} record Drag(int startX, int startY, int endX, int endY) implements UserAction {} record Scroll(int amount) implements UserAction {}
record Click(int x, int y) implements UserAction {} record Drag(int startX, int startY, int endX, int endY) implements UserAction {} record Scroll(int amount) implements UserAction {} Recordでクラス定義の ボイラープレートを減らせる (getter, equals, hashCode, toString) パターンの網羅性を担保、 defaultを省略できる
-> "No action provided"; case Click(int x, int y) when x > 0 && y > 0 -> "Clicked at positive coordinates"; case Click(int x, int y) -> "Clicked at " + x + ", " + y; case Drag(int startX, int startY, int endX, int endY) -> "Dragged from " + startX + " to " + endX; case Scroll(int amount) when amount > 0 -> "Scrolled down by " + amount; case Scroll(int amount) when amount < 0 -> "Scrolled up by " + amount; case Scroll _ -> "No scrolling"; }; ガードパターンで 条件を追加できる 無名パターンで 変数が不要な時は 省略できる モデルの構造を変えずに 機能追加がしやすい nullの判定も できる
i when i < 0 -> "Negative number: " + i; case 0 -> "Zero"; default -> "Positive number: " + value; }; return switch (year) { case int y when (y % 400 == 0) -> y + "ӞͰ͢"; case int y when (y % 100 == 0) -> y + "ӞͰ͋Γ·ͤΜ"; case int y when (y % 4 == 0) -> y + "ӞͰ͢"; };
oldLoc = new Point(1, 2); // x࠲ඪΛมߋͯ͠৽͍͠ϨίʔυΛ࡞ Point newLoc = oldLoc with { x = 0; }; // xͱy࠲ඪΛ2ഒʹͯ͠৽͍͠ϨίʔυΛ࡞ Point finalLoc = newLoc with { x *= 2; y *= 2; }; シンプルに書けるし Recordの イミュータブルな 特性をいかせる