Operators
7.1 Standard Operators
Arithmetic + - * / % **, comparison == != < > <= >=, logical && || !, bitwise & | ^ ~ << >> >>>, assignment = += -= *= /= %= **=, increment ++ --, ternary ? :.
7.2 Groovy-Specific Operators
user?.address?.city (null if any part is null) name ?: "Anonymous" Elvis assignment (Groovy 3+) name ?= "default"
people*.name (collects a property from each element) method(*list), [*list1, *list2], [*:map1, *:map2] Spaceship (compareTo) a <=> b → -1, 0, 1 Range (inclusive/exclusive) 1..10, 0..<size, 1<..5 (Groovy 4) Membership (isCase) x in [1, 2, 3], x !in list Identity (Groovy 3+) a === b (same object) Find (creates a Matcher) text =~ /\d+/ Match (whole string) "123" ==~ /\d+/ → true def m = str.&toUpperCase Method reference (Groovy 3+) Direct field access obj.@field (bypasses the getter) "42" as Integer, [1, 2] as Set instanceof / !instanceof x !instanceof String (Groovy 3+) Left shift / append list << 4, sb << "x" Subscript (getAt/putAt) map['key'], list[1..3] closure() → call()
Implication (Groovy 4, in groovy-contracts)
def user = null
println user?.name ?: "No user"
def names = [[name: "Ana"], [name: "Bo"]]*.name // [Ana, Bo]
def nums = [1, 2, 3]
def more = [0, *nums, 4] // [0, 1, 2, 3, 4]
def merged = [a: 1, *:[b: 2]] // [a:1, b:2]
println([3, 1, 2].sort { a, b -> b <=> a })
println 5 in 1..10, 'x' in ['x', 'y'], 7 !in [1, 2]
def upper = "groovy".&toUpperCase
println upper()7.3 Operator Overloading
a.mod(b) (remainder in Groovy 5) a | b, a & b, a ^ b or, and, xor a << b, a >> b leftShift, rightShift next(), previous() -a, +a, ~a
negative(), positive(), bitwiseNegate() a[b], a[b] = c getAt(b), putAt(b, c) a in b / switch case a <=> b, <, >
equals (or compareTo for Comparable)
class Money {
BigDecimal amount
Money plus(Money o) { new Money(amount: amount + o.amount) }
Money multiply(Number n) { new Money(amount: amount * n) }
String toString() { "\$$amount" }
}
println new Money(amount: 5) + new Money(amount: 3) // $8
println new Money(amount: 5) * 2