Type inference

Gosu supports type inference, in which Gosu can often infer the type of an item without requiring explicit type declarations in the Gosu code. For instance, Gosu can determine the type of a variable from its initialized value:

var length = 12
var list = new java.util.ArrayList()

In the first line, Gosu infers the length variable has the type int. In the second line, Gosu infers the type of the list variable is of type ArrayList. In most cases, it is unnecessary to declare a variable’s type if Gosu can determine the type of the initialization value.

The Gosu syntax for explicit declarations of the type of the variable during declaration is:

var c : MyClassName = new MyClassName()

For typical code, Gosu coding style is to omit the type and use type inference to determine the variable’s type.

Another standard Gosu coding style is to use a coercion on the right side of the expression with an explicit type. For example, suppose you use a class called Vehicle, which has a subclass Car. If the variable v has the compile-time type Vehicle, the following code coerces the variable to the subtype:

var myCar = v as Car