Defining generic types and functions
Note: This section is a stub.
We have showed how to use generic types, but not how to define them. This section explains how to define generic types. We also discuss generic functions.
Defining a generic type
This is a simple generic stack type:
class Stack<T> private var array = [] as Array<T> def create() as void end def isEmpty() as Boolean return self.array == [] end def push(o as T) self.array.append(o) end def pop() as T self.array.removeAt(-1) end end
You can use it like this:
def Main() as void var s = Stack() as <Int> s.push(2) s.push(5) Print(s.pop()) -- 5 Print(s.isEmpty()) -- False end
Keep these things in mind when you define generic types:
- You can use type variables (T in the stack example) in type declarations within a generic type, and they behave almost like ordinary types.
- Two type variable types are not compatible with each other. A type variable type is compatible with Object, however.
- Values with type variable types only support operations available for the Object type, such as assignment and the == operator.
- You cannot cast a value to a type variable type.
- You can mix static and dynamic typing within the body of a generic type.
Generic functions
Alore also supports generic functions and methods. They have one or more type variables associated with them. Here is a simple generic function:
def First<T>(a as Array<T>) as T return a[0] end var ia = [3, 5] as Array<Int> var sa = ['foo', 'bar'] as Array<Str> First(ia) -- 3 First(sa) -- 'foo'
You can replace the type variable (T in above example) with any type when calling the function. Usually the type checker can infer the value of the type variable, but you can also give it explicitly:
First(ai) as <Int>
Note that the syntax is similar to constructing instances of generic types.