Skip to content
Abe Pralle edited this page Sep 7, 2022 · 6 revisions

which

Syntax

Single line and multi-line case syntax can be intermixed.

Multi-line case Syntax

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

Single Line case Syntax

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

Notes

  • 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 C switch.

Example

# 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

Inline Which

Syntax

which{ condition:result || condition:result || result }

Description

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.

Example

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
...
Clone this wiki locally