Automatic type downcasting
To improve the readability of Gosu code, Gosu
automatically downcasts a type after a typeis
or typeof expression if
the type is a subtype of the specified type. Automatic type downcasting
is particularly valuable for if
and switch code blocks.
Gosu confirms that the typed object has the more specific subtype within
the code block. Accordingly, Gosu implicitly downcasts the variable’s
type to the relevant subtype for the block. There is no need to explicitly
cast the type with an as TYPE statement.
A common pattern for this feature is shown below.
var VARIABLE_NAME : TYPE_NAME
// This code requires SUBTYPE_NAME to be a subtype of TYPE_NAME
if (VARIABLE_NAME typeis SUBTYPE_NAME) {
// Use the VARIABLE_NAME variable as a SUBTYPE_NAME without explicit casting
...
}
For example, the following code shows a variable declared
as an Object, but automatically
downcast to String when
referenced within the if
code block.
var x : Object = "nice"
var strlen = 0
if ( x typeis String ) {
strlen = x.length // x automatically downcast to a String which has a length property
}
Note that length
is a property on String,
not Object. The automatic
downcasting of the variable eliminates the need to explicitly cast it.
The following code is equivalent to the previous code, but has an unnecessary
explicit cast.
var x : Object = "nice"
var strlen = 0
if ( x typeis String ) {
strlen = (x as String).length // Do not need to explicitly cast x as a String
}
Best practice recommends utilizing automatic downcasting when it occurs and eliminating unnecessary explicit casting.
