Type Constraints

Type Constraints on generics allow restrincting the allowed generics into a subtype.

Type constraints are defined with one or many where clauses, in whose the actual constraint is defined.

Subtypes

Let 'A be a type parameter, and 'B be another type, the form 'A : 'B declares that 'A must be a subtype of 'B.

In the following example, 'A must be a subtype of Animal.

type MyList['A] = Array['A]
           ╰╴Unrecognized character
                       ╰╴Unrecognized character
where 'A : Animal
          ╰╴Unrecognized character
thp

You can have multiple where clauses, and they act like and:

type MyList['A] = Array['A]
           ╰╴Unrecognized character
                       ╰╴Unrecognized character
where 'A : AquaticAnimal
          ╰╴Unrecognized character
where 'A : LandAnimal
          ╰╴Unrecognized character
thp

In the previous example, 'A must be subtype of both Aquatic and Land animal.

and subtype constraint

A different notation A & B can also be used. This is the same.

type MyList['A] = Array['A]
           ╰╴Unrecognized character
                       ╰╴Unrecognized character
where 'A : AquaticAnimal & LandAnimal
          ╰╴Unrecognized character
thp

or subtype constraint

A type can be subtyped by either A or B with notation A | B:

type MyList['A] = Array['A]
           ╰╴Unrecognized character
                       ╰╴Unrecognized character
where 'A : LandAnimal | AirAnimal
          ╰╴Unrecognized character
thp
type ItemOf['A] = @IdxType('A, Int)
           ╰╴Unrecognized character
                          ╰╴Unrecognized character
where 'A : Array
          ╰╴Unrecognized character
fun Item(Type 'A, Array('A) _) -> Type {
              ╰╴Unrecognized character
                        ╰╴Unrecognized character
@IdxType('A, Int)
             ╰╴Unrecognized character
} Item(String, [...]) Item([...]) fun Item['A](Array['A] a) {
         ╰╴Unrecognized character
@IdxType('A, Int)
             ╰╴Unrecognized character
} val items = ["a", "b", "c"] Item(items) == String
thp