Skip to content

Operators

Philip Ford edited this page Sep 16, 2018 · 20 revisions

Contents

Overview

Groovy uses the same operators as in Java, but adds some others.

The Elvis Operator: ?:

A more concise ternary operator which says, "if the expression is null, do this."

def sampleText
 
// Normal ternary operator.
def ternaryOutput = (sampleText != null) ? sampleText : 'Hello Groovy!'
 
// The Elvis operator in action. We must read: 'If sampleText is not null assign
// sampleText to elvisOuput, otherwise assign 'Viva Las Vegas!' to elvisOutput.
def elvisOutput = sampleText ?: 'Viva Las Vegas!'

Direct field access operator: @.

TBD

The Null-Check Operator: ?.

TBD

The Spaceship Operator: <=>

TBD

The Spread Operator: *

TBD

The Spread-Dot Operator: *.

TBD

Operator Overloading

While Groovy can use the same operators as Java, operators are all implemented by methods in Groovy. This means we can do operator overriding in our own classes. This is very useful and can make more concise code.

Operators and their corresponding methods

Operator Method
a + b a.plus(b)
a - b a.minus(b)
a * b a.multiply(b)
a ** b a.power(b)
a / b a.div(b)
a % b a.mod(b)
a | b a.or(b)
a & b a.and(b)
a ^ b a.xor(b)
a++ or ++a a.next()
a-- or --a a.previous()
a[b] a.getAt(b)
a[b] = c a.putAt(b, c)
a << b a.leftShift(b)
a >> b a.rightShift(b)
a >>> b a.rightShiftUnsigned(b)
switch(a) { case(b) : } b.isCase(a)
~a a.negate()
-a a.negative()
+a a.positive()
a == b a.equals(b)
a != b ! a.equals(b)
a <⇒ b a.compareTo(b)
a > b a.compareTo(b) > 0
a >= b a.compareTo(b) >= 0
a < b a.compareTo(b) < 0
a ⇐ b a.compareTo(b) ⇐ 0

Example: Overloading +

class Money {
   def amount

   Money plus(Money other) {
       new Money(amount: this.amount + other.amount)
   }

   boolean equals(Object other) {
       amount == other.amount
   }

   int hashCode() {
       amount.hashCode()
   }

   String toString() {
       amount
   }
}

def m1 = new Money(amount: 100)
def m2 = new Money(amount: 1)

assert (m1 + m2).amount == 101  // plus()
assert m1 + m2 == new Money(amount: 101)  // equals() and plus()

References

Clone this wiki locally