Why can't I use type-checked variable in first condition as type-casted variable in second condition?

huangapple go评论76阅读模式
英文:

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 &amp;&amp; a.foo()) {
.....
}

This works fine-

if(a instanceOf A &amp;&amp; ((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 运算符 只是简单地返回 truefalse,对其操作数的类型没有影响。

从 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 &amp;&amp; actual.foo()) {
    // ...
}

huangapple
  • 本文由 发表于 2020年4月7日 22:51:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/61082854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定