Last Updated: February 25, 2016
·
5.66K
· will-lp

Groovy's instanceof

When using @TypeChecked or @CompileStatic, Groovy's instanceof automagically cast the object inside the if block:

import groovy.transform.TypeChecked as TC

@TC class Instanceof {
  static main(args) {
    def foo = new Foo(bar: "bar bar")
    assert new Instanceof().foobar(foo) == "bar bar"
  }

  def foobar(foo) {
    if (foo instanceof Foo) {
      foo.bar // no need to cast :-)
    }
  }
}

@TC class Foo { String bar }