Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 75 ]

where:
a | b | c
-1 | 1 | 2
0 | 1 | 1
1 | 2 | 1

One of my favorite Groovy shortcuts is what we can do if we combine the spaceship
operator with the Elvis operator. Suppose we have an object, which has three fields
that define an account balance, first name and last name, we might want to sort these
balances highest first, but then order them by the last name and then first name:


class Balance {
String first
String last
BigDecimal balance
String toString() { "$last, $first : $balance"}
}

We can express the sort very succinctly using a combination of spaceship
comparators and Elvis operators:


a.balance<=>b.balance ?: a.last<=>b.last ?: a.first<=>b.first

Let's take a look at this in practice with a Spock test:


given: "we have a few customer account objects"
def accounts = [
new Balance(balance: 200.00,
first:"Fred", last:"Flintstone"),
new Balance(balance: 100.00,
first:"Wilma", last:"Flintstone"),
new Balance(balance: 100.00,
first:"Barney", last:"Rubble"),
new Balance(balance: 100.00,
first:"Betty", last:"Rubble"),
]
when: "we sort these with spaceship Elvis operators"
accounts.sort { a, b ->
a.balance <=> b.balance ?:
a.last <=> b.last ?: a.first <=> b.first
}.each { println it }
then: "the accounts are sorted by balance - last - first"
"""Rubble, Barney : 100.00
Rubble, Betty : 100.00
Flintstone, Wilma : 100.00
Flintstone, Fred :200.00"""
Free download pdf