Generics and interfaces

Type parameters, invariance, interfaces and type tests.

vlatest

Generics are available on functions and classes. Type parameters are declared in angle brackets after the name.

Generic functions

Type arguments are inferred at the call site, so you never write them out:

fn identity<T>(x: T) -> T {
    return x
}

fn main() {
    println(identity(3))      // 3
    println(identity("hi"))   // hi
}

Several parameters infer independently:

fn pair<A, B>(a: A, b: B) -> string {
    return "{a}/{b}"
}

fn main() {
    println(pair(1, "x"))
    println(pair(2.5, true))
}

Generic classes

A class can take a type parameter, and its fields and methods can use it:

class Box<T> {
    var value: T

    constructor(value: T) {
        this.value = value
    }

    fn get() -> T {
        return this.value
    }
}

fn main() {
    let b = Box<int>(5)
    println(b.get())          // 5
    let s = Box<string>("hi")
    println(s.get())          // hi
}

Supply the type argument at the call site. The constructor does not infer it, so write Box<int>(5) rather than Box(5).

Generic shapes that lower

Generic code that stays within a simple call, arguments in and one result out, lowers to machine code. Keep generics to leaf shapes: functions that transform a value, and classes that hold one.

Pattern Lowers
identity<T>(x: T) -> T yes
Box<T> with one field, a constructor, and fn get() -> T yes
generic class with an inferred type argument no
generic class combined with inheritance no
returning a List<T> from a generic function no

Variance

Variance is neither annotated nor checked. Box<Dog> and Box<Animal> are the same type to the compiler, so a generic class will not stop you writing a value of the wrong type into it. Use an interface when you need a real contract.

class Animal {
    var name: string

    constructor(name: string) {
        this.name = name
    }
}

class Box<T> {
    var value: T

    constructor(value: T) {
        this.value = value
    }
}

fn main() {
    let b = Box<Animal>(Animal("rex"))
    println(b.value.name)   // rex
}

No generic type aliases

There is no type declaration at all, so a generic alias is not something you can write. A const is a value. If you want a name for a type, document it in a comment:

// UserId is an int issued by the users service.
fn greet(id: int) -> string {
    return "user {id}"
}

fn main() {
    println(greet(7))
}

Next steps