Switch expressions

JSONiq follows the W3C standard for switch expressions. The following explanations, provided as an informal summary for convenience, are non-normative.

Figure 50. SwitchExpr

SwitchExpr

Figure 51. SwitchCaseClause

SwitchCaseClause

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.

Note that if there is an object or array in the base switch expression or any case expression, a JSONiq-specific type error JNTY0004 will be raised, because objects and arrays cannot be atomized and the W3C standard requires atomization of the base and case expressions.

Example 106. 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 107. 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 108. 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 109. A switch expression

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

Result (run with Zorba): foo


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