x_8taw
Last Updated: February 25, 2016
·
1.16K
· will-lp
13aa0f93a57ca225067d6ff9aa49e341

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 }
Say Thanks
Respond