gpt4 book ai didi

Groovy "not instanceof"特性

转载 作者:行者123 更新时间:2023-12-01 12:23:48 28 4
gpt4 key购买 nike

在尝试评估非 instanceof 条件时,我发现了我在 Groovy 2.4.7、1.6.0 JVM 中没有预料到的行为。

总之:

class Foo {    
static Boolean bar() {
String x = "Personally, I don't really like King Crimson"
return (!x instanceof Integer)
}
}

我预计 Foo.bar() 会返回 true,因为 x 不是 Integer 的实例,但是 Foo.bar() 返回 false。相比之下,以下返回 true:
class Foo {    
static Boolean bar() {
String x = "Personally, I don't really like King Crimson"
return !(x instanceof Integer)
}
}

这个问题是学术性的,但出于好奇:这是语言中的错误还是我误解了 instanceof 应该如何工作?

最佳答案

这是operator precedence的案例...!发生在 instanceof 之前,所以它实际上是在检查:

(!x) instanceof Integer
所以它将 String 转换为 bool 值( !'Hello'false 因为字符串包含一些文本。
然后查看 bool 值是否是 Integer 的实例(不是)
因此 false如果你把 !在括号外(如在您的第二个版本中),然后它首先执行 instanceof,并否定结果,为您提供您期望的答案
为 Groovy 编辑 3+
在 groovy 3 中,有一种新方法可以使用 !instanceof :
return x !instanceof Integer

关于Groovy "not instanceof"特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41810151/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com