-
Notifications
You must be signed in to change notification settings - Fork 8
which
Abe Pralle edited this page Sep 7, 2022
·
6 revisions
Single line and multi-line case
syntax can be intermixed.
which (expression)
case N
<code for case N>
case M
<code for case M>
case O, P
<code for cases O and P>
others # optional
<code for any other cases>
endWhich
which (expression)
case N: <code for case N>
case M: <code for case M>
case O, P: <code for case O and P>
others: <code for any other cases>
endWhich
- Cases do not require a break or escape as they do in C.
- Empty cases do not fall through to the next case as they do in C.
- Case values can be literals, variables, and/or complex expressions.
- A
which
with only literal-value cases is converted into a fast Cswitch
.
# Print: 1st, 2nd, 3rd, 4th, 5th, ... 10th
forEach (rank in 1..10)
print rank
which (rank)
case 1: println "st"
caseNext: println "nd"
caseNext: println "rd"
others: println "th"
endWhich
endForEach
which{ condition:result || condition:result || result }
The inline which is an expression that evaluates to one of two or more results based on various conditions. It is analogous to C's decision operator (AKA ternary operator), although the inline which
can have any number of alternatives.
If the value is omitted from a condition:value
pair, and only condition
is given, the condition will be used as the value as well. So which{ a || b }
is shorthand for which{ a?:a || b }
. This rule does not apply to the final case in a which{}
, which is always a value without a condition.
forEach (rank in 1..10)
println "$$ place" (rank,which{rank==1:"st" || rank==2:"nd" || rank==3:"rd" || "th"})
endForEach
# Output
1st place
2nd place
3rd place
4th place
...