Search

Dark theme | Light theme

March 4, 2020

Groovy Goodness: Using !instanceof Operator

Groovy 3 adds the !instanceof operator to check if an object is not an instance of a type. This is a shorthand for using instanceof and then negate the result. It shows how little changes can make code easier to read.

In the following example we use the old way to check if object is not an instance of a type and the new !instanceof operator:

// Check using !(obj instanceof type) 
// if object is not an instance of type.
assert !("Groovy is awesome!" instanceof Number)

// Since Groovy 3 we can use !instanceof to check
// if object is not an instance of a type.
assert 42 !instanceof String

Written with Groovy 3.0.1.