Use typeis expressions for automatic downcasting

As a best practice, Guidewire recommends that you use typeis expressions to compare the type of an object with a given subtype. After a typeis expression, Gosu automatically downcasts subsequent references to the object if the object is of the type or a subtype of the original typeis expression. Use typeis expressions for automatic downcasting to improve the readability of your code by avoiding redundant and unnecessary casts.

The automatic downcasting of typeis expressions is particularly valuable for if statements and similar Gosu flow of control structures. Within the code block of an if statement, you can omit explicitly casting the object as its subtype. Gosu confirms that the object is the more specific subtype and considers it be the subtype within the if code block.

The following sample Gosu code shows a pattern for how to use a typeis expression with an if statement.

var variableName : TypeName             // Declare a variable as a high-level type. 
 
if (variableName typeis SubtypeName) {  // Downcast the variable to one of its subtypes. 
    ...                                 // Use the variable as its subtype without explicit casting.
}

The following sample Gosu code follows the pattern and declares a variable as an Object. The if condition downcasts the variable to its more specific subtype, String.

var x : Object = "nice"    // Declare a String variable as type Object.
var strlen = 0
 
if (x typeis String) {     // Downcast the Object variable to its subtype String.
  strlen = x.length        // Use the variable as a String without explicit casting.
}

Because Gosu propagates the downcasting from the if condition into the if code block, the expression x.length is valid. The length property is on String, not Object.

The following sample Gosu code is equivalent to the preceding example, but it redundantly casts the variable as a String within the if code block.

var x : Object = "nice"          // Declare a String variable as type Object.
var strlen = 0
 
if (x typeis String) {           // Downcast the Object variable to its subtype String.
  strlen = (x as String).length  // Explicit casting as String is redundant and unnecessary.
}

See also