Switch expressions

Figure 40. SwitchExpr

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 100. 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 101. 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 102. 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 103. A switch expression

switch (2)
case 1 + 1 return "foo"
case 2 + 2 return "bar"
default return "none"
        

Result (run with Zorba): foo


Example 104. 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