Java 20がリリースされましたが、いろいろいじってると変な落ち方をしていて、どうもバグぽいので報告しました。
※ 追記 4/19 JDK20.0.1がリリースされて修正されてます。
再現コードこんな感じ。
public class PatternSample { sealed interface Type { record Bulk(int price) implements Type {} record Packed(int price) implements Type {} } record Product(String name, Type type) {} public static void main(String[] args) { Product item = new Product("meat", new Type.Bulk(250)); int total = switch(item) { case Product(var n, Type.Packed(int price)) -> price; case Product(var n, Type.Bulk(int price)) -> price; }; System.out.println(total); } }
こんな感じでエラーでます。
複数のcase句でレコードパターンの2番目にレコードがあって、両方のcase句で内側のレコードの値を使うと落ちます。
レコードの定義がこうなってたら大丈夫。
record Product(Type type, String name) {}
あと、case句の片側でprice
を使わなくても大丈夫。
case Product(var n, Type.Packed(int price)) -> price; case Product(var n, Type.Bulk(int price)) -> 0;
ということで、メーリングリストに報告してます。
Record Pattern with swich has something wrong
前回はJava 10だったので、次回はJava 30ですかね。
Java 10のコンパイラバグを見つけた - きしだのHatena