Spar - parameterized types

sparSpar generalizes Java classes by allowing parameterization. For example, the Java tutorial shows a stack class that can hold elements of arbitrary type. If we wanted to restrict the stack to elements of a given type, we could implement a separate class for each type, but it is much more useful to implement a generic, parameterized, stack. In Spar this is possible as follows:
class TypedStack(| type t |) {
    static final int STACK_EMPTY = -1;
    t[] stackelements;
    int topelement = STACK_EMPTY;

    void push( t e ){
        stackelements[++topelement] = e;
    }
    t pop() {
        return stackelements[topelement--];
    }
    boolean isEmpty(){
        return ( topelement == STACK_EMPTY );
    }
}
An instance of this class could be used as follows:
TypedStack(|char|) s = new TypedStack(|char|)();

s.push( 'a' ); s.push( 'b' ); char c = s.pop();

Parameterization is not restricted to type parameters. In Spar, parameterized classes are always expanded at compile-time.

Interfaces

Just like classes, Spar interfaces can be parameterized:
interface Collection(| type t |){
    void add( t obj );
    void delete( t obj );
    t find( t obj );
    int currentCount();
}
A class can inherit this interface as follows:
Class Bag(| type t |) implements Collection(| type t |) {
    . . .
};
An important use of parameterized interfaces is the Array interface.

Last modified Sat May 13 15:50:56 2017 UT by Kees van Reeuwijk.