Generics in Gosu

Generics abstract the behavior of a type to support working with multiple types of objects, and are especially useful for implementing collections such as lists and maps in a type-safe way. At compile time, each use of the collection can specify the specific type of its items. For example, instead of just referring to a list of objects, you can refer to a list of Address objects or a list of Vehicle objects. To specify a type, add one or more parameters types inside angle brackets (< and >). This syntax that specifies the type of a collection or another item of unknown type is called parameterizing a generic type. For example:
uses java.util.*

var mylist = new ArrayList<Date>()    
var mymap = new Map<String, Date>()   // A map that maps String to Date
In this example, ArrayList<Date> is an array list of date objects. The Map<String, Date> is a map that maps String to Date.
The Gosu generics implementation is compatible with the Java 1.5 generics implementation, and adds these improvements:
  • Gosu type inference greatly improves readability. You can omit unnecessary type declarations, which is especially important for generics because the syntax tends to be verbose.
  • Gosu generics support array-style variance of different generic types. In Java, this code results in a compilation error:
    ArrayList<Object> mylist;
    mylist = new ArrayList<String>()
    In comparision, this similar Gosu code works:
    var mylist : ArrayList<Object>
    mylist = new ArrayList<String>()
  • Gosu types support reified generics. Reified generics preserve generic type information at run time. In complex cases, you can check the exact type of an object at run time, including any parameterization. In contrast, Java discards this information completely after compilation, so it is unavailable at run time.
    Note: Even in Gosu, parameterization information is unavailable for all native Java types, because Java does not preserve this information beyond compile time. For example, the runtime type of java.util.List<Address> in Gosu returns the unparameterized type java.util.List.
  • Gosu includes shortcut initialization syntax for common collection types so you do not need to see the generics syntax, which tends to be verbose. For example:
    var strlist = { "a", "list", "of", "Strings" }
    Although this code does not specify a type, the strlist variable is statically typed. Gosu detects the types of objects that you use to initialize a variable and uses type inference to determine that strlist has the type java.util.ArrayList<java.lang.String>. This generics syntax represents a list of String objects.

See also