英文:
Why can't I use type-checked variable in first condition as type-casted variable in second condition?
问题
类 A
{
布尔值 foo() {
返回 真;
}
}
为什么以下代码会产生语法错误?<br>
*方法在类型中未定义*
如果(a 是 A 的实例 并且 a.foo()) {
.....
}
这段代码可以正常工作-
如果(a 是 A 的实例 并且 ((A)a).foo()) {
.....
}
英文:
class A
{
boolean foo() {
return true;
}
}
Why is the following giving syntax error?<br>
method is undefined for type
if(a instanceOf A && a.foo()) {
.....
}
This works fine-
if(a instanceOf A && ((A)a).foo()) {
.....
}
答案1
得分: 1
对于人类来说,a
的类型是 A
,这是因为有 instanceof
检查。然而,编译器并不像这样工作,因此您仍然需要将 a
强制转换为 A
。
英文:
To a human it's clear that a
is of type A
because of the instanceof
check. The compiler doesn't work like that though and therefore you still need to cast a
to A
.
答案2
得分: 1
先前,instanceof
运算符 只是简单地返回 true
或 false
,对其操作数的类型没有影响。
从 Java 14 开始,instanceof
支持模式匹配(或在此处查看规范预览 here)。您可以内联声明一个新变量,该变量将是 instanceof
的目标类型,仅在检查成功时才会如此。
例如,您的代码将如下所示:
if(a instanceof A actual && actual.foo()) {
// ...
}
英文:
Previously, the instanceof
operator simply returned true
or false
and had no effect on the types of its operands.
As of Java 14, instanceof
supports pattern matching (or see spec preview here). You are able to declare a new variable inline that will be of the instanceof
's target type if and only if the check was successful.
For example, your code would look like
if(a instanceof A actual && actual.foo()) {
// ...
}
专注分享java语言的经验与见解,让所有开发者获益!
评论