Chapter 4
[ 73 ]
We can set up a Spock test to assert that this is true for various values of a:
given:
def b = 'value1'
def c = 'value2'
and: "a ternary expression"
def result1 = (a? b : c)
and: "the logical equivalent using if and condition"
def result2
if (a) {
result2 = b
} else {
result2 = c
}
expect: "these expressions are equivalent for various values of a"
result1 == result2
where:
a << [1,0,2,true,false]
The Elvis operator's behavior is best illustrated as a version of the ternary operator.
So, (a? : b) is equivalent to (a? a : b). The use of the Elvis operator makes more
sense in the light of our previous discussion on Groovy Truth where the Boolean
condition used can be something other than a regular expression:
given:
def b = 'value1'
and: "a ternary expression"
def result1 = (a ?: b)
and: "the logical equivalent using if and condition"
def result2
if (a) {
result2 = a
} else {
result2 = b
}
expect: "these expressions are equivalent for various values of a"
result1 == result2
where:
a << [1,0,2,true,false]