Parameterizing a method

You can add a finer granularity of type usage by adding generic type modifiers to a method, immediately after the method name. In Gosu, this syntax of adding the generic type modifiers is called parameterizing the method. In other languages, this syntax of adding the generic type modifiers is known as making a polymorphic method with a generic type.

If the parameterized method needs information about the runtime type of the type parameter, you must add the modifier reified to the method declaration. Some parameterized methods do not require information about the runtime type of the type parameter. For these methods, the modifier reified is optional.

For example, in the following code, the class is not parameterized but one method is parameterized and does not require information about the type of T at run time:

class GenericTypesTester<T> {
  // Return whether the argument is a String
  public function isStringType<T>(t : T) : boolean {
//  public reified function isStringType<T>(t : T) : boolean { // This declaration is also valid
    return t typeis String
  }
}

In the method’s Gosu code, the symbol T can be used as a type and Gosu matches T to the type of the argument passed into the method.

The following code uses this class and the parameterized method:

var t = new ReificationTester()
print("'abc' is a String: " + t.isStringType("abc"))
print("123 is a String: " + t.isStringType(123))

Running this code prints the following messages:

'abc' is a String: true
123 is a String: false