Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy "not instanceof" peculiarity

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?

like image 234
Jay Edwards Avatar asked Jan 23 '17 15:01

Jay Edwards


1 Answers

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

Edit for Groovy 3+

In groovy 3 there's a new way of doing this using !instanceof:

return x !instanceof Integer
like image 104
tim_yates Avatar answered Sep 23 '22 20:09

tim_yates