SWITCH - Conditional Operator
7.31 | 7.40 | 7.54
... SWITCH type( [let_exp]
WHEN const1 THEN [let_exp] result1
[ WHEN const2 THEN [let_exp] result2 ]
[ ELSE [let_exp] resultn ] ) ...
A conditional expression
with the conditional operator
SWITCH has a result,
result, that is specified by a case distinction. Either a value with
the data type specified by
type is produced or a class-based exception raised. The following can be specified for
- A non-generic data type
#character as a symbol for the operand type.
- If the data type required in an operand position is unique and fully identifiable, this type is used.
- If the operand type is not fully identifiable, an operand with a statically identifiable type must
be specified after the first
THEN. This type is then used. In particular,
THROWs cannot be specified after
All operands specified after
THEN must be convertible to the data type determined by
type. In the case of reference variables, an
up cast must be possible.
operand in the parenthesis is the value checked in the case distinction. This is a
general expression position. It must be followed by at least one
WHEN. Literals and
constants can be specified for
WHEN. It must be possible to
compare them with
This can be followed by any number of
WHENs with further constant values.
ELSE can be specified at the end. This expression compares the values
of the operand
operand with the specified constant values, one by one, and
THEN for which the values of operand and constant are identical for
the first time. The selected
determines the result of the conditional expression. If no matches are found, the
result specified after
ELSE is selected. If
ELSE is not specified, the result is the initial value of the data type
If an item specified after
ELSE can be
selected, either the result is set or a class-based exception is raised, just as with a conditional expression
LET expression can be specified
in front of the operand
operand, after every
THEN. and after
ELSE to define local auxiliary fields.
- Text symbols for
constcannot be specified after
- A conditional expression with
SWITCHhas the same meaning as the following conditional expression with
[ WHEN operand = const2 THEN result2 ]
[ ELSE resultn ] )
SWITCH in an operand position in a loop. The loop is exited when the exception after
ELSE is caught.
CLASS cx_overflow DEFINITION INHERITING FROM cx_static_check. ENDCLASS. DATA(out) = cl_demo_output=>new( ). DO. TRY. out->write( SWITCH string( sy-index WHEN 1 THEN 'one' WHEN 2 THEN 'two' WHEN 3 THEN 'three' ELSE THROW cx_overflow( ) ) ). CATCH cx_overflow. out->display( ). EXIT. ENDTRY. ENDDO.