Product SiteDocumentation Site

5.5.2. Switch expressions

SwitchExpr
Figure 5.34. SwitchExpr

A switch expression evaluates the expression inside the switch. If it is an atomic, it compares it in turn to the provided atomic values (with the semantics of the eq operator) and returns the value associated with the first matching case clause.
Example 5.93. A switch expression
switch ("foo")
case "bar" return "foo"
case "foo" return "bar"
default return "none"
Result (run with Zorba):
bar

If it is not an atomic, an error is raised.
Example 5.94. A switch expression
switch ({ "foo" : "bar" })
case "bar" return "foo"
case "foo" return "bar"
default return "none"
Result (run with Zorba):
An error was raised: can not atomize an object item: an object has probably been passed where an atomic value is expected (e.g., as a key, or to a function expecting an atomic item)

If no value matches, the default is used.
Example 5.95. A switch expression
switch ("no-match")
case "bar" return "foo"
case "foo" return "bar"
default return "none"
Result (run with Zorba):
none

The case clauses support composability of expressions as well.
Example 5.96. A switch expression
switch (2)
case 1 + 1 return "foo"
case 2 + 2 return "bar"
default return "none"
Result (run with Zorba):
foo

Example 5.97. A switch expression
switch (true)
case 1 + 1 eq 2 return "1 + 1 is 2"
case 2 + 2 eq 5 return "2 + 2 is 5"
default return "none of the above is true"
Result (run with Zorba):
1 + 1 is 2