Groovy has some operators that vanilla Java doesn't. Here's a quick reference:

`<=>`

(Spaceship)Example:

`a <=> b`

is equivalent to `a.compareTo(b)`

`?:`

(Elvis)Example:

`x ?: y`

is equivalent to `x != null ? x : y`

`=~`

(Find)Example:

`Matcher m = "abc" =~ /a/`

`==~`

(Match)Example:

`assert "abc" ==~ /\w+/`

Note this is a full match not a partial.`~`

(Create pattern)Example:

`~/abc/`

is equivalent to `new Pattern(/abc/)`

`*.`

(Spread)Example:

`a*.b`

is equivalent to `a.collect { it.b }`

`.&`

(Method reference)Example:

`Closure c = a.&b`

gives you a reference to the method "b()" on object "a" that you can pass around as a Closure.`.@`

(Property access)Example:

`def c = a.@b`

gives you the value of the property "b" on object "a" directly (*i.e.*without going through the getter). This can be useful on horrible classes like

`java.awt.Dimension`where the type of a public property is different to the return type of its getter. Most other uses of it are probably best avoided.

`?.`

(Null-safe dereference)Example:

`a?.b`

is equivalent to `a == null ? null : a.b`

`as`

(Type coercion)Example:

`new Date() as String`

is equivalent to `new Date().toString()`

which is a trivial example but you can do quite exciting type conversions by overriding `asType`

.`is`

(Object identity)Example:

`a is b`

is equivalent to `a == b`

in Java.kthxbye.

## No comments:

Post a Comment