Typecase Statement



next up previous contents index
Next: Begin Statement Up: Statements Previous: Tagcase Statement

Typecase Statement

A variable or expression in Theta has an apparent type known to the compiler, and the compiler guarantees that the actual type of the object denoted by the variable or computed by the expression is a subtype of that type. Sometimes it is useful to determine what the actual type of the object is, or to narrow its apparent type to some subtype. This is accomplished by the typecase statement. The form of this statement is
typecase <expr> <type_arm> [<type_arm>]* [others ":" <body>] end
where
        <type_arm> -> when <type_designator> [ ( <idn> ) ] ":" <body>
The expression expr is evaluated, and the actual type [tex2html_wrap2934] of the resulting object is then used to select a type_arm. The type_arms are considered in order, and the first one whose type designator denotes a supertype of type [tex2html_wrap2936] is selected: the object is assigned to the idn of that type_arm (if present), and the corresponding body is executed. Within this body the idn can be used to refer to the object with the type specified in the arm; the idn is defined only in this body. When execution of the body completes, control continues at the statement after the typecase. An others arm always matches, but provides no useful additional information about the object's type.

A legal typecase statement satisfies the following constraints:

  1. No type occurs in more than one arm.
  2. The type of each arm must be a proper subtype of the apparent type of expression expr. A proper subtype of a type includes all subtypes except for the type itself, so that it is always narrower than the type itself.
  3. If "S" is a subtype of "T" and both "S" and "T" are used in type arms, the type arm for "S" must precede the type arm for "T". (The more specific type must precede the more general type since otherwise the arm with the more specific type is useless.)

The following example assumes "set" and "bag" are both subtypes of type "collection", and "stack" is a subtype of "bag":

        x: collection
        ...
        typecase x
            when stack(y):   ...% y is a stack in this arm
            when bag(z):     ...% z is a bag in this arm
            others:          ...% x must be used as a collection in this arm
            end
The others arm will be selected if "x"'s actual type is "set" (or some other "collection" type that is not a subtype of "stack" or "bag").



next up previous contents index
Next: Begin Statement Up: Statements Previous: Tagcase Statement



theta-questions@lcs.mit.edu