I have discovered behaviour that I hadn't anticipated within Groovy 2.4.7, 1.6.0 JVM when attempting to evaluate a not instanceof condition.
in summary:
class Foo {
static Boolean bar() {
String x = "Personally, I don't really like King Crimson"
return (!x instanceof Integer)
}
}
I would anticipate that Foo.bar() would return true because x is not an instance of Integer however Foo.bar() returns false. In contrast the following returns true:
class Foo {
static Boolean bar() {
String x = "Personally, I don't really like King Crimson"
return !(x instanceof Integer)
}
}
The issue is academic, but out of curiousity: is this a bug in the language or have I misunderstood how instanceof is supposed to work?
It's a case of operator precedence...
!
occurs before instanceof
, so it's actually checking:
(!x) instanceof Integer
So it's converting String to a boolean (!'Hello'
is false
as the string contains some text.
Then seeing if the boolean is an instanceof Integer (which it isn't)
hence false
If you put the !
outside the brackets (as in your second version) then it does the instanceof first, and negates the result, giving you the answer you'd expect
In groovy 3 there's a new way of doing this using !instanceof
:
return x !instanceof Integer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With