When automatic downcasting occurs

Automatic downcasting occurs when executing the following types of statements.

  • if statements
  • switch statements
    uses java.util.Date
    
    var x : Object = "neat"
    switch ( typeof x ){
      case String :
        print( x.charAt( 0 ) )   // x is automatically downcast to type String
        break
      case Date :
        print( x.Time )          // x is automatically downcast to type Date
        break
    }
  • The true portion of ternary conditional expressions
    x typeis String ? x.length : 0   // x is automatically downcast to type String

    The automatic downcast occurs only for the true portion of the ternary expression. In the false portion, the variable reverts to its original type.

The automatic downcast is terminated and the object is interpreted as being of its original type when any of the following conditions occurs.

  • Reaching the end of the code block’s scope
    • The end of an if code block
    • The end of a case code block within a switch statement
    • The end of the true portion of a ternary conditional expression
  • Assigning any value to the variable that you checked with typeis or typeof. This behavior applies only to if and switch statements.
  • Assigning any value to any part of an entity path that you checked with typeis or typeof. This behavior applies only to if and switch statements.
  • An or keyword in a logical expression
  • The end of an expression negated with the not keyword
  • In a switch statement, a case section does not use automatic downcasting if the previous case section is not terminated by a break statement. The following switch statement demonstrates this rare behavior.
    uses java.util.Date
    
    var x : Object = "neat"
    switch( typeof x ){
      case String :
        print( x.charAt( 0 ) )  // x is automatically downcast to type String
      case Date :               // Code execution falls through to next case
        print( x.Time )         // x reverts to original type of Object which does not have Time property
        break
    }

    When the x object of type Object attempts to access a non-existent Time property, a compile error occurs. To work around this behavior, explicitly cast the x object to a type Date as shown below.

    print( (x as Date).Time )  // Explicitly cast x to type Date to access the Time property