Example 5-6. Example:
typecase a when INT then ... when FLT then ... when $A then ... else ... end |
typecase_statement ==> typecase identifier when type_specifier then statement_list { when type_specifier then statement_list } [ else statement_list ] end |
An operation that depends on the runtime type of an object held by a variable of abstract type may be performed inside a typecase statement. The identifier must name a local variable or an argument of a method. If the typecase appears in an iterator, then the mode of the argument must be once; otherwise, the type of object that such an argument holds could change.
On execution, each successive type_specifier is tested for being a supertype of the type of the object held by the variable. The statement list following the first matching type specifier is executed and control passes to the statement following the typecase. Within each statement list, the type of the typecase variable is taken to be the type specified by the matching type specifier unless the variable's declared type is a subtype of it, in which case it retains its declared type. It is not legal to assign to the typecase variable within the statement lists. If the object's type is not a subtype of any of the type specifiers and an else clause is present, then the statement list following it is executed. It is a fatal error for no branch to match in the absence of an else clause. The declared type of the variable is not changed within the else statement list. If the value of the variable is void when the typecase is executed, then its type is taken to be the declared type of the variable.