Basic type coercion

Gosu provides coercion or casting syntax to cast an expression to a specific type. The syntax is shown below.

Coercions.makeTYPEFrom(expression)

The expression must be compatible with the type. The following table shows the results of casting a simple numeric expression into one of the Gosu-supported data types.

Expression

Data type

Result or error

Coercions.makeBooleanFrom(5 * 4)

Boolean

true

Coercions.makeStringFrom(5 * 4)

String

20

Coercions.makeArrayFrom(5 * 4)

Not applicable

Does not compile. Method does not exist.

The as keyword can be used to cast an array type to another compatible array type. For example, String is a subtype of Object, so an array of type String can be cast to an array of type Object.

var objArray : Object[]
objArray = new String[] {"a", "b"} as Object[]   // Can cast String[] to Object[]

The reverse operation of casting an Object to a String is invalid, as demonstrated below.

var objArray2 = new Object[1]
objArray2[0] = "aString"
var strArray = objArray2 as String[]   // Run-time error attempting to cast Object[] to String[]

The compiler can detect and produce a compilation error when two referenced types are incompatible. For example, an Integer[] can never be converted to a String[], so the following code statements produce a compilation error.

var strArray2 : String[]
strArray2 = new Integer[] {2, 3} as String[]   // Compilation error attempting to cast Integer[] to String[]

In some cases, you know that all the objects in an array are of a particular subtype of the defined type of the array. In other cases, you filter an array to retrieve only objects of a particular subtype. As shown in a preceding code example, you cannot use the as keyword to convert an array to an array of a subtype. Instead, you can use the Gosu enhancement method cast to make an array of the subtype. You can then perform operations on the new array that are specific to the subtype and not available to the parent type. If you filter an array by element type and do not use the cast method, the result retains the type of the original array.

The following code demonstrates how to use the cast method.
var objArray3 = new Object[1]
objArray3[0] = "aString"
var strArray3 = objArray3.cast(String) // String array

var objArray4 = new Object[2]
objArray4[0] = "anotherString"
objArray4[1] = 42
var strArray4 = objArray4.where(\aid -> aid typeis String).cast(String) // String array
var objArray5 = objArray4.where(\aid -> aid typeis String) // Object array

You cannot use the cast method to convert incompatible types. The compiler does not detect this type of error. The following code produces a run-time error.

var strArray5 : String[]
strArray5 = new Integer[] {2, 3}.cast(String)   // Run-time error attempting to cast Integer[] to String[]