When automatic downcasting occurs
Automatic downcasting occurs when executing the following types of statements.
ifstatementsswitchstatementsuses 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
trueportion of ternary conditional expressionsx typeis String ? x.length : 0 // x is automatically downcast to type StringThe automatic downcast occurs only for the
trueportion of the ternary expression. In thefalseportion, 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
ifcode block - The end of a
casecode block within aswitchstatement - The end of the
trueportion of a ternary conditional expression
- The end of an
- Assigning any value to the variable that you
checked with
typeisortypeof. This behavior applies only toifandswitchstatements. - Assigning
any value to any part of an entity path that you checked with
typeisortypeof. This behavior applies only toifandswitchstatements. - An
orkeyword in a logical expression - The end of an expression
negated with the
notkeyword - In a
switchstatement, acasesection does not use automatic downcasting if the previouscasesection is not terminated by abreakstatement. The followingswitchstatement 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
Objectattempts to access a non-existentTimeproperty, a compile error occurs. To work around this behavior, explicitly cast the x object to a typeDateas shown below.print( (x as Date).Time ) // Explicitly cast x to type Date to access the Time property
