Groovy, lesson 4
Programs need to act differently depending on their data: charge children less, warn when it's too hot. Groovy's tools for this will look familiar if you know Java, with a few useful upgrades.
if and elseThe condition goes in parentheses and each branch in braces. Groovy checks the conditions from top to bottom and runs only the first branch whose condition is true.
| Operator | Meaning |
|---|---|
== != | equal / not equal |
< > | less / greater than |
<= |
2 exercises to try what you just read.
>=| less / greater or equal |
<=> | compare: -1, 0 or 1 |
Unlike Java, == in Groovy compares values, so "abc" == "abc" is true even for two
different string objects. (To check whether two variables point to the very same object, Groovy
has ===.)
Combine conditions with && (and), || (or) and ! (not):
&& and || stop early: if the left side decides the answer, the right side is skipped.
Groovy lets any value stand in a condition. null, 0, an empty string and an empty list or map
count as false; everything else counts as true. So if (name) means "if name is not null and not
empty". Use it to make checks shorter, but keep comparisons explicit when the meaning would be
unclear.
For a quick choice between two values, use the ternary operator condition ? a : b:
The Elvis operator ?: gives a fallback when a value is false by Groovy truth:
def displayName = name ?: "Guest".
switchGroovy's switch can match far more than exact values: a range checks membership, a list checks
whether the value is in it, and a closure in braces runs a test. As an expression with ->
arms, it produces a value and there is no fall-through to worry about:
0..9 is a range including both ends; 10..<100 stops before 100. The first matching case wins,
and default covers everything else. Prefer this form over the old statement form with break.
A cinema charges by age: children under 13 pay 5, people aged 65 or older pay 7, and everyone else pays 12. Read an age (a whole number, 0 or more) and print the price.
Sample input:
Sample output:
A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap
years only if they are also divisible by 400. Read a year and print leap or common.
Sample input:
Sample output:
def reader = System.in.newReader()
int temp = reader.readLine().trim().toInteger()
if (temp > 25) {
println "Wear a hat"
} else if (temp > 10) {
println "A T-shirt is fine"
} else {
println "Bring a jacket"
}boolean canRide = age >= 8 && height >= 120
boolean weekend = day == "Sat" || day == "Sun"def advice = temp > 25 ? "Wear a hat" : "Bring a jacket"def size = switch (n) {
case 0..9 -> "small"
case 10..<100 -> "medium"
default -> "large"
}70Price: 72024leap