Tuesday, 6 January 2009

Groovy Truth and the instanceof Operator

I just stumbled across a little gotcha which would have failed compilation in Java, but in Groovy compiles but doesn't do what the developer intended.
    if (!obj instanceof SomeEnum) throw new IllegalArgumentException()
// do something with obj.name()
Clearly, the intention was to throw IllegalArgumentException if obj is not the correct type, but instead the code was throwing MissingMethodException from the access to obj.name().

The problem is missing braces. What Groovy is actually evaluating is
    if (false instanceof SomeEnum)
!obj evaluates to false as obj is not null. The correct code would be:
    if (!(obj instanceof SomeEnum)) throw new IllegalArgumentException()

No comments: