dav*_*hew 3 java instanceof pattern-matching java-record
I have Java 19, and I am attempting to do some simple pattern-matching on a record that I created. However, Java is giving me a very confusing compilation error. Here is the simplest example I could make that causes the error.
public class ExpressionTypeIsASubsetOfPatternType
{
public record Triple(int a, int b, int c) {}
public static void main(String[] args)
{
System.out.println("Java Version = " + System.getProperty("java.version"));
final Triple input = new Triple(1, 2, 3);
if (input instanceof Triple t)
{
System.out.println("Made it here");
}
}
}
Run Code Online (Sandbox Code Playgroud)
And here is the error that it gives me when I try to run/compile.
$ java ExpressionTypeIsASubsetOfPatternType.java
ExpressionTypeIsASubsetOfPatternType.java:15: error: expression type Triple is a subtype of pattern type Triple
if (input instanceof Triple t)
^
1 error
error: compilation failed
Run Code Online (Sandbox Code Playgroud)
Surprisingly enough, googling this error showed up nothing useful. I am so used to punching in an error and immediately seeing the problem. I imagine that it is because this feature is so new.
Anyways, the closest thing I could find is a bug that is related, but definitely not the same issue that I am dealing with.
Finally, here is the relevant info about my java version.
$ java --version
openjdk 19 2022-09-20
OpenJDK Runtime Environment (build 19+36-2238)
OpenJDK 64-Bit Server VM (build 19+36-2238, mixed mode, sharing)
Run Code Online (Sandbox Code Playgroud)
$ javac --version
javac 19
Run Code Online (Sandbox Code Playgroud)
HTNW 的答案是正确的响应,但我发现编译器的这种行为并不理想,因为它没有考虑空引用。这里有一些不一致之处:
String s = null;
if (s instanceof String) {}
Run Code Online (Sandbox Code Playgroud)
String s = null;
if (s instanceof String string) {}
Run Code Online (Sandbox Code Playgroud)
第一个选项将编译,第二个选项将给出错误“模式类型‘字符串’与表达式类型相同”。这意味着instanceof可以用作空检查,但如果使用模式匹配则不能。没有意义。
| 归档时间: |
|
| 查看次数: |
1582 次 |
| 最近记录: |