Product SiteDocumentation Site

5.7.5. Typeswitch expressions

TypeswitchExpr
Figure 5.51. TypeswitchExpr

CaseClause
Figure 5.52. CaseClause

A typeswitch expressions tests if the value resulting from the first operand matches a given list of types. The expression corresponding to the first matching case is finally evaluated. If there is no match, the expression in the default clause is evaluated.
Example 5.154. Typeswitch expression
typeswitch("foo")
case integer return "integer"
case string return "string"
case object return "object"
default return "other"
Result (run with Zorba):
string

In each clause, it is possible to bind the value of the first operand to a variable.
Example 5.155. Typeswitch expression
typeswitch("foo")
case $i as integer return $i + 1
case $s as string return $s || "foo"
case $o as object return [ $o ]
default $d return $d
Result (run with Zorba):
foofoo

The vertical bar can be used to allow several types in the same case clause.
Example 5.156. Typeswitch expression
typeswitch("foo")
case $a as integer | string return { "integer or string" : $a }
case $o as object return [ $o ]
default $d return $d
Result (run with Zorba):
{ "integer or string" : "foo" }