Object> myObj(int a, int b) { return name -> switch(name) { case "a" -> a; case "b" -> b; case "mul" -> a * b; case "add" -> a + b; default -> throw new RuntimeException(); }; } class MyFunc() { int apply(int a, int b) { return a + b; } }
{ /** 量り売り */ record Bulk(int price, int unit) implements Type {} /** パッケージ */ record Packed(int price) implements Type {} } record Item(Type type, int amount) {} var cart = List.of( new Item(new Packed(300), 3), new Item(new Bulk(250, 100), 230));
3), new Item(new Bulk(250, 100), 230)); int total = cart.stream() .mapToInt(item -> switch(item) { case Item(Packed(int price), int amount) -> price * amount; case Item(Bulk(int price, int unit), int amount) -> price * amount / unit; }).sum();
• 代数的データ型の直和型の実現と考えれる • 例: Type型はBulk型かPacked型かどちらかになる sealed interface Type { /** 量り売り */ record Bulk(int price, int unit) implements Type {} /** パッケージ */ record Packed(int price) implements Type {} }