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:

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.