Sealed型 ● java.nio.Bufferのように継承を使う場合 ● コンストラクタをパッケージプライベートにすると限定できる ● javaパッケージであれば新たに追加されることはない ● アプリケーションクラスではJARをあとから追加が可能 ● 可能な型を限定できない ● sealed型で限定 sealed interface Type { record Bulk(int price, int unit) implements Type {} record Packed(int price) implements Type {} } sealed interface Type permits Bulk, Packed {} record Bulk(int price, int unit) implements Type {} record Packed(int price) implements Type {}
データの処理を考える ● こんな値を合計する record Product(String name, Type type) {} record Item(Product product, int amount) {} var cart = List.of( new Item(new Product("餃子", new Packed(300)), 3), new Item(new Product("牛肉", new Bulk(250, 100)), 230));
Switch式 ● Java 14で正式導入 int total = cart.stream() .mapToInt(item -> switch(item) { case Item(Product(var n, Packed(int price)), int amount) -> price * amount; case Item(Product(var n, Bulk(int price, int unit)), int amount) -> price * amount / unit; }).sum();