Groovy "not instanceof" 特点
Groovy "not instanceof" peculiarity
我在 Groovy 2.4.7、1.6.0 JVM 尝试评估 not instanceof 条件时发现了我没有预料到的行为。
总结:
class Foo {
static Boolean bar() {
String x = "Personally, I don't really like King Crimson"
return (!x instanceof Integer)
}
}
我预计 Foo.bar() 会 return 为真,因为 x 不是 Integer 的实例,但是 Foo.bar() return是假的。相比之下,以下 return 为真:
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
因此它将字符串转换为布尔值(!'Hello'
是 false
,因为字符串包含一些文本。
然后查看布尔值是否是 Instanceof Integer(不是)
因此false
如果你把 !
放在方括号外(就像在你的第二个版本中一样),那么它首先执行 instanceof,然后否定结果,给你你期望的答案
编辑 Groovy 3+
在 groovy 3 中有一种使用 !instanceof
:
的新方法
return x !instanceof Integer
我在 Groovy 2.4.7、1.6.0 JVM 尝试评估 not instanceof 条件时发现了我没有预料到的行为。
总结:
class Foo {
static Boolean bar() {
String x = "Personally, I don't really like King Crimson"
return (!x instanceof Integer)
}
}
我预计 Foo.bar() 会 return 为真,因为 x 不是 Integer 的实例,但是 Foo.bar() return是假的。相比之下,以下 return 为真:
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
因此它将字符串转换为布尔值(!'Hello'
是 false
,因为字符串包含一些文本。
然后查看布尔值是否是 Instanceof Integer(不是)
因此false
如果你把 !
放在方括号外(就像在你的第二个版本中一样),那么它首先执行 instanceof,然后否定结果,给你你期望的答案
编辑 Groovy 3+
在 groovy 3 中有一种使用 !instanceof
:
return x !instanceof Integer