Handling any values of different types with the switch statement
The switch statement is used to conditionally execute a block of code. Unlike the if and if ... else statements, the switch statement can have a number of possible execution paths.
The
switch statement operates on an expression of the
any type (see also
Handling the any type). At runtime, the type of the value is examined, and the
case clause for that type is executed if there is one, otherwise the
default clause is executed. If the
any value is empty, the
default clause is always executed.
If the
default clause is not present and none of the
case clauses match the type of the value passed to the
switch statement, then the
switch statement throws
Exception with type set to
UnmatchedTypeException. See also the description of the
Exception type in the
API Reference for EPL (ApamaDoc) .
The switch statement names the expression as an identifier with the as keyword followed by an identifier to name the value. In each case clause block, the identifier has the same type as the case clause.
If the expression is a simple identifier (that is, it is referring to a variable or parameter), then the as Identifier part can be omitted. The new local retains the same name.
The following code example shows the usage of the switch statement in an action which returns a string, where the case clauses use return statements to return from the action. The identifier value in each clause has the same type as the case clause.
Example:
action getStringOrBlank(any value) returns string {
switch(value) {
// value will be of type float in this block
case float : { return "float "+ value.toString(); }
// value will be of type string in this block
case string: { return value; }
// value will be of type decimal in this block
case decimal: { return "decimal "+value.toString(); }
// value will be of type integer in this block
case integer: { return "integer: "+ value.toString(); }
// value will be of type sequence<string> in this block
case sequence<string> : { return " ".join(value); }
// value will be of any type in this block
default: { return ""; }
}
}