-
Notifications
You must be signed in to change notification settings - Fork 0
Operators
Philip Ford edited this page Sep 16, 2018
·
20 revisions
Groovy uses the same operators as in Java, but adds some others.
The use of .@ forces usage of the field instead of the getter for that field.
Example:
class User {
public final String name
User(String name) { this.name = name}
String getName() { "Name: $name" }
}
def user = new User('Bob')
assert user.name == 'Name: Bob' Here the user.name call triggers a call to the getter for name. If you want to retrieve the field instead of calling the getter, you can use the direct field access operator:
assert user.@name == 'Bob' 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!'TBD
TBD
TBD
TBD
TBD
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.
| 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 |
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()