Skip to content
Adam
Language

Generics

Types, routines and methods with type parameters, checked per instance.

Examples: res\examples\language\generics holds small, commented programs for this page's features, each listing the output it prints; run one with adam build <file> -r.

Declaring and using

A type (a record, an object, an interface, an overlay, an array, a routine type or an alias), a routine or a method declares type parameters after its name: <T>, <K, V>. A use of a generic type names every type argument (Stack<string>), and a record literal of an instance names them too.

generics_basics.adam
module exe generics_basics;

type
  Pair<K, V> = record
    Key: K;
    Value: V;
  end;

  Stack<T> = object
    hidden FItems: array of T;

    // AItem on top
    method Push(const AItem: T);
    begin
      setlength(self.FItems, len(self.FItems) + 1);
      self.FItems[len(self.FItems) - 1] := AItem;
    end;

    // The top item, taken off
    method Pop(): T;
    var
      LItem: T;
    begin
      LItem := self.FItems[len(self.FItems) - 1];
      setlength(self.FItems, len(self.FItems) - 1);
      return LItem;
    end;
  end;

// The larger of A and B
func Max<T>(const A: T; const B: T): T;
begin
  if A > B then
    return A;
  end;
  return B;
end;

var
  GPair: Pair<string, int32>;
  GStack: Stack<string>;

begin
  GPair := Pair<string, int32>(Key: "answer", Value: 42);
  println("{} = {}", GPair.Key, GPair.Value);
  println("{} {}", Max(3, 7), Max<float64>(2.5, 1.5));
  GStack.Push("first");
  GStack.Push("second");
  println("{}", GStack.Pop());
  println("{}", GStack.Pop());
end.
output on x86_64-windows-gnu and x86_64-linux-gnu
answer = 42
7 2.5
second
first

A generic routine is called with its type arguments named (Max<float64>(2.5, 1.5)) or left to the call's arguments (Max(3, 7)), which must agree exactly: no conversion picks a type argument.

Checking

There are no constraints on type parameters. A generic's body is checked once per instance, with its type arguments in place, so Max<T> may use > and the instance decides whether its type has it. An error only one instance has is reported at the generic's line, with a note at the use that made the instance.

A method of a generic type's instance is checked and compiled only when something uses it; virtual methods, init, copy, done, operators and property accessors are always made.

Instances

Each distinct list of type arguments is one instance in the whole program, made once and shared by every unit that names it; a generic no one instantiates makes no code. Where a plain routine and a generic instance take a call equally well, the plain routine wins. A generic method is never virtual, override or abstract, and a generic routine is never external.

The standard library's List<T>, Map<K, V> and Set<T> are generic objects: System.Collections.

↑ ↓ moveEnter openEsc close