Type Parameters

A class can have several type parameters that can be used to get extensible behavior. For example, the Array class has one type parameter:

    class Array<T> {

        function new() {
            // ...
        }

        function get( pos : Int ) : T {
            // ...
        }

        function set( pos : Int, val : T ) : Void {
            // ...
        }
    }

Inside the Array class, the type T is abstract which means its fields and methods are not accessible. However when you declare an array you need to specify its type : Array<Int> or Array<String> for example. This will act the same as if you had replaced all types T in the Array declaration by the type you're specifying.

The type parameter is very useful in order to get strict typing of containers such as Array, List, and Tree. You can define your own parameterized classes with several type parameters for your own usage when you need it.

Constraint Parameters

While it's nice to be able to define abstract parameters, it is also possible to define several constraints on them in order to be able to use them in the class implementation. For example :

    class EvtQueue<T : (Event, EventDispatcher)> {
        var evt : T;
        // ...
    }

In this class, although the field evt is a class paramater, the typer knows that it has both types Event and EventDispatcher so it can actually access it like if it was implementing both classes. Later, when an EvtQueue is created, the typer will check that the type parameter either extends or implements the two types Event and EventDispatcher. When multiple constraint parameters are defined for a single class parameter, as in the example above, they should be placed within parenthesis in order to disambiguate from cases where more class parameters are to follow.

Type parameter constraints are a powerful feature that lets a developer write generic code that can be reused across different applications.

«« Object Oriented Programming - Enums »»

version #6947, modified 2009-09-05 17:11:31 by justsee