Types
Generics
Generic classes and functions, how type arguments are inferred or given explicitly with ::<T>, invariance, how each instantiation is checked, T::member and type constructors.
since 0.1.0-alpha.1linuxwindowswasm
Description
A class, a function or a method can take type parameters: class Box<T>, R identity<R>(R x), U map<U>(...). In a type, an instantiation is written Name<T1, ...>, as in Box<int>.
The compiler infers type arguments, in this order:
- from the types of the constructor or call arguments, including through containers (an
Array<U>parameter against anArray<int>argument givesU = int) and through inheritance (aBox<U>parameter against an argument whose class derives fromBox<int>, such asclass IntBox : Box<int>, givesU = int); - from the target type of the initializer, assignment or return that receives the result.
When inference is not enough, or you want to state the types, give them at the call with ::<...>: Box::<int>(), identity::<string>("x"), items.remap::<string>(fn).
Generic class and functions
use io::console;
class Box<T> {
T item;
T get() => this.item;
U map<U>((T) => U f) => f(this.item);
}
R identity<R>(R x) => x;
Box<int> a = Box(5);
console.writeln(a.get());
console.writeln(a.map((n) => "n=${n}"));
Box<string> b = Box::<string>("hi");
console.writeln(b.get());
console.writeln(identity(41) + 1);
console.writeln(identity::<string>("x"));
void demo() {
var f = identity::<int>;
console.writeln(f(7));
}
demo();
5
n=5
hi
42
x
7
Rules
Writing and inferring type arguments.
- A static member of a generic class is shared by every instantiation and is written with the bare
class name (
Box::count); it cannot use the class's type parameters (lang.static-members). - A type position uses angle brackets:
Name<T1, T2>. Instantiations nest:Array<Array<int>>. - A generic class is always written with its type arguments, in every type position: a variable, a parameter, a return type, a field, a function type, a base clause, a
catch, anistest and amatchpattern.Array xs,catch (Box b)andclass Sub : Box { }are compile errors, and so is a wrong count (Map<int>) or arguments on a class that takes none (P<int>):
error: 'Array' is generic: write its type arguments, as in 'Array<int>'
error: 'Map' takes 2 type arguments, not 1
error: 'P' is not generic
- A call uses the turbofish,
callee::<T1, ...>(args).f<T>(x)written without::is a comparison, never a generic call. - That comparison is then rejected. A type name as an operand of
<,>,<=or>=is a compile error that names the turbofish, because a type is not a value and has no order.Box<int>(4)parses as(Box < int) > (4). The error says thatBoxis a type, not a value, so it cannot be an operand of<, and it names the turbofish (Box::<T>(...)). A note gives the construction,Box::<int>(...).- Spellings that do not parse get the same note: a
?in the type arguments (Box<P?>(p)), two or more of them (Map<string, int>()), or a nested list. - This changes behaviour for existing programs:
var n = Box<Box<int>>(b);used to compile withnabool, andf(Two<int, string>(1))used to compile as twoboolarguments. - The same holds for
==and!=: a bare type name is not a value in operand position, so no operator resolves on it.int == stringis a compile error with the same message (it used to betrueon--runand not lowerable on--ir).x is intis unchanged; equality of types is left to the planned Type objects.
- Spellings that do not parse get the same note: a
- The turbofish with no argument list,
identity::<int>, is a pinned reference to the generic function as a value. An unpinned reference,var f = identity;, is a compile error that suggests the turbofish. - An explicit list is all-or-nothing and exact. Its length must equal the generic arity of the constructor, function or method:
Box::<int, int>(1)and a one-argument list for a two-parameter function are errors. - An explicit list needs a declared function, method or constructor. It cannot be applied to a closure or another function value.
- Receiver class arguments are independent of a method's explicit list:
items.remap::<string>(fn)supplies only the method's parameter. - A call binds a generic method's type parameters once: from the receiver's type arguments, from an inherited method's base clause (
class K : G<int>bindsG'sT := intfor everyGmethod called on aK, through any chain of clauses), from explicit::<...>arguments, and then from the value arguments, a lambda argument's declared parameter types and its return type. A lambda's written return type binds exactly, as::<...>does:xs.map(string (x) => "n" + x)bindsUtostring; without one, the type its body returns binds it. This holds in method and constructor calls. Every argument, every typed lambda parameter and the return type are checked against that one binding. When several value arguments determine the same type parameter, it binds to the single most specific common supertype of all of them, and their order never matters: withvoid eq<T>(T a, T b)and astring? v, botheq(v, "x")andeq("x", v)bindTtostring?; aDogand anAnimalbindAnimal, and so do aDogand aCatwhose one common base isAnimal. Bindings from explicit::<...>arguments, the receiver and base clauses come first and are never widened. The same rule types a conditional, amatch, an array literal,??and a lambda's returns (lang.merged-types). - An optional argument lifts:
Noneis set aside, the common supertype of the rest is taken, and the result is optional again. ADog?and anAnimalbindAnimal?. No other union is formed. - A bare literal argument beside a typed argument does not decide the binding. It takes the binding the typed argument gives, the way a literal takes a declared type: with a
float f,pick(f, 0)andpick(0, f)bindfloat; with abyte b,pick(b, 1)bindsbyte, andpick(b, 300)is the usual out-of-range error; with achar c,pick(c, 'x')bindschar. A float literal never becomes an integer, so with anint i,pick(i, 2.5)is an error. - Inference never widens a number otherwise:
intandfloathave no common supertype, so two typed numbers of different types, or two literals of different kinds (pick(1, 2.5)), are an error. Inside a generic body, a number beside a value of the body's own type parameter takes that parameter:U bump<U>(U x) => pick(x, x + 1);bindsU, and the number is the contextual numeric boundary described below. A non-numeric value there is an error. - When the arguments have no common supertype, or more than one equally specific (two base classes, two interfaces), the call is a compile error; write the binding explicitly, as in
pick::<float>(1, 2.5):
error: cannot infer type argument 'T' for 'pick': 'int' and 'float' have no common supertype; write the type arguments explicitly, e.g. 'pick::<...>(...)'
- Inside a generic body its own type parameters are rigid. A value of type
Tconverts toTitself, to a union that holdsT(such asT?), and to a type parameter of a generic function being called, which then binds toT. It converts to no other type: with a fieldT keep,int y = this.keep;,takeInt(this.keep),int f() => this.keep;andU other<U>() => this.keep;are compile errors, whateverTis instantiated to. The same holds where the conversion is less visible: arithmetic with a number gives aT(this.keep + 1and0 + this.keepareTs, soint a = 0 + this.keep;andacc += this.keep;into anintare errors, whileT t = this.keep + 1;is fine); a construction typed by its target (Box<int> b = Box(this.keep);) is checked likeBox::<int>(this.keep); a condition or an operand of&&,||or!(if (this.keep)) must be abool; and a conditional with aTarm (c ? this.keep : 0) is aT, so it is an error into anint. The one exception is a call to an overloaded free or namespace function, inside a generic function, that passes a value of the function's own type parameter: with overloadsenc(int)andenc(string),enc(x)insidearr<T>is resolved again for each instantiation, and an instantiation that no overload accepts is a compile error at that call. A typed lambda parameter must name the same parameter. A non-numeric concrete value ("s",None,true) is never known to beT, wherever theTsits in the target and whatever brings the value there: withT g(T x),void put(Array<T> a)andT? h(T? x), the callsthis.g("s"),this.put(["a"])andthis.h("a")are compile errors, and so areArray<T> xs = ["a"];,this.xs = ["a"];, aBox<string>or aK : Box<string>passed for aBox<T>, and a lambda body that gives astringwhere aTis expected. A number in any of those places is a contextual numeric boundary, and the next rule decides it. - A number converts to a type parameter only where the parameter is bound to a number. Inside a generic body
T z() => 0;,c ? this.keep : 0,T x = 0;,this.g(5),this.put([1])andvs.add(aFloat)on anArray<T>are accepted, and each binding is checked: onBox<float>the0is afloat, onBox<string>the call or construction that bindsTis a compile error whose note points at the0. A member nothing calls on aBox<string>binds nothing, so it is not checked there. Noneis not a value of a type parameter:Tmay be instantiated with a type that does not admitNone(string), so inside the generic bodyNone, and a value that may beNone(aT?, any union holdingNone), does not convert toT.return None;from a function returningT,T f<T>(T? x) => x;andv = None;into a fieldT vare compile errors (cannot return 'None' as 'T',cannot assign 'None' to 'T'). AT?reachesTonly by narrowing: afterif (x != None), or after an early exit such asif (x == None) { return d; },xis aT. WriteT?where the value may be absent.
Variance.
- Generics are invariant: a
Box<int>is not aBox<float>, even thoughintconverts tofloat. - Inside a generic class,
thishas the class's type at its own type parameters: insideclass Self<T> : Box<T>,thisis aSelf<T>and therefore aBox<T>. It converts toBox<T>, but not toBox<string>orSelf<string>. - Invariance holds across inheritance too. A subclass, or a class implementing an interface, converts to its base only at the instantiation its base clause names, read with the value's own type arguments. With
class SubBox<T> : Box<T>, aSubBox<int>is aBox<int>and converts to it, but not toBox<string>. Withclass IntBox : Box<int>, anIntBoxis aBox<int>and nothing else. The rule is the same through interfaces (class Cell<T> : IGet<T>makes aCell<int>anIGet<int>), through an interface that extends another, and across any number of base levels.
Type tests.
- Type arguments are erased at run time, so a test can check only the class. An
istest or amatchpattern naming a generic class is legal only when the subject's static type already fixes its arguments, and the arguments written must be those: withx : Array<int> | string,x is Array<int>narrowsxtoArray<int>. Withv : IShape(whereclass Cup<T> : IShape) nothing fixesT, and withc : Cup<int> | Cup<string>the members disagree; both are compile errors. A test that can never be true is one too:x is Array<string>withx : Array<int> | int, ors is Cup<int>withs : string.
error: cannot test for 'Cup<int>' at run time: generics are erased and 'IShape' does not fix the type arguments of 'Cup'
error: 'Array<string>' can never match 'Array<int> | int'
- A subject whose class derives from the tested class fixes its arguments through the base clause (
class IntBox : Box<int>: anIntBoxtests as aBox<int>), and so does a base or interface the tested class's own clause names (class Jar<T> : IHolder<T>: anIHolder<string>tests as aJar<string>). - A test against a generic function's own type parameter (
match (m) { E => … }insideE castTo<E>(Model m)) is exact: the function is compiled once per concrete binding, and each copy tests that class. A class-level type parameter cannot be tested:
error: cannot test for 'T' at run time: 'T' is a type parameter of class 'Holder' and generics are erased
Members of a type-parameter value.
- Generics have no bounds, so a member read or a method call on a value of type
T(or on a value computed from one) is not checked in the generic body itself:x.name()withx : Tcompiles there, and its result has no checkable type in the body; avarinitialized with it depends on the type parameter in the same way, and a type test on it that names a generic class is a compile error, because nothing fixes the class's arguments. - Instead every instantiation is checked, as C++ checks a template: each use of a value of type
Tis a demand onT, and every type bound toTmust meet the demands of the members the program uses with that binding. A demand is a field read or store, a method call (its name, its number of arguments and their types), indexing, a call of the value, an operator (+,<, unary-, ...),for … in, and string interpolation ("${x}"callstoString()).==and!=are met by every type, except one that (itself or through a base) declares a user(==): then the use is checked asa == bwith that type is, so a(==)(int)rejectssame(D(), D())just as it rejectsD() == D(). A string+stringifies its other operand and is no demand on it. - A binding is the bound type itself, not its spelling: two classes named
Din different namespaces are two bindings. A type parameter the call does not fix takes the argument's own static type (all([D()])bindsTtoD;nn(D())for a parameterT? xbindsTtoD). When no concrete type follows from the arguments and the body uses the parameter, the call is an error: "cannot check type parameter 'T' of 'all': it is not inferred here; write the type arguments (::<...>)". - A binding meets a demand exactly as non-generic code with that type would: a union or optional type has no members until narrowed (it does have
==), a function type has none, an interface has its declared members,<needs a number,string,charor a class declaring(<), andtoStringis not universal. - The check is lazy, per member:
Array<D>demands nothing ofD, while callingjoinToStringon anArray<D>demandsD.toString(). A binding is checked against the member it is used with and everything that member reaches with it: a generic that passes itsTto another generic, or a class member that calls another member of its class, inherits the callee's demands, and a class bound through a base clause (class IntBox : Box<int>,class Sub<T> : Box<T>) is checked the same way. Because a dispatched call can run another body than the one it names, the program is treated as closed: a call that binds a method's own type parameters binds those of every override and implementation of that method too, and constructing a class binds the members it overrides or implements (a member of an interface or base), for a class without parameters of its own through its generic base (class DBox : Box<D>). Forming a function value binds as a call does:rd::<D>, orBox::showtyped as(Box<D>) => string. - Where a demand's result flows into a concrete type (
int first<A>(A a) => a.xs[0];), the bound type must produce a compatible one. - A method call or an operator on a value of type
Tis chosen at run time by its name and number of arguments alone. When the bound type has two or more methods of that name and count (m(string s)andm(int x),(==)(Money)and(==)(int)), the one declared first runs, inherited ones before the class's own, whatever the argument types. The binding therefore depends on the declaration order: it compiles when the overload the use needs is the first one, and fails when it is another, with or without an override:type 'B' bound to 'T' of 'callInt' has two methods 'm' taking 1 argument, m(string) and m(int): the use needs m(int), but it runs the first of them, m(string). The standard library's own generic equality follows the same rule.Array.contains,Array.indexOfandPair/Triple==compile for an element type whose(==)(Money)is declared before its(==)(int), and fail for one declared the other way round. The operators amatcharm on aTvalue calls (==for a value arm,>=and<=for a range arm) are checked for this rule only; an arm is no other demand onT. - A use guarded by a type test that narrows the value to a concrete class (
match (x) { C => x.s },if (x is C)) is checked against that class and is no demand. A use guarded only by a run-time condition is still a demand. - A failing binding is a compile error at the call, construction or base clause that binds
T, with notes at the use and at the calls that reach it:
error: type 'D' bound to 'T' of 'rd' has no field 's'
note: required by 'x.s' at main.lev:3
- Checking a binding re-checks what it reaches with that binding. A chain of distinct generics has no length limit, but polymorphic recursion -- a generic reaching itself again with a growing binding,
w<T>callingw<W<T>>-- is rejected after 32 re-entries, as C++ rejects an infinite instantiation: "generic instantiation check exceeded the depth limit (32); this instantiation graph may be unbounded". - Generics stay erased at run time: one compiled body serves every binding.
T::member.
- Inside a generic function, the left side of
::may be one of that function's own type parameters:A::FromInt(n)calls the labeled constructorFromIntof whatever typeAis at the call. - The member is checked for each concrete type used. If the type lacks the member, the error names the type and points to both the
A::memberuse and the call that instantiated it. T::works only for type parameters of the function. A class-level parameter is rejected: "'T' is a class-level type parameter".
Type constructors.
- A type parameter may stand for a generic type that takes an argument, written
F<A>. Inference bindsFto the generic name:F<A>againstArray<int>givesF = ArrayandA = int, and the result typeF<B>keeps the container. When several arguments determineF, it takes the common supertype of their whole types: aSub<int>and aBase<int>, whereSub<T> : Base<T>, giveF = Basein either order. - This is an advanced idiom. Prefer ordinary methods for everyday code.
Examples
T::member and a type constructor:
T::member and a type constructor
use io::console;
class Meters {
int n = 0;
new FromInt(int v) { this.n = v; }
}
class Wrapper<T> {
T item;
new Of(T v) { this.item = v; }
}
A decode<A>(A witness, int n) => A::FromInt(n);
F<B> mapIt<F, A, B>(F<A> c, (A) => B fn) => c.map(fn);
Meters m = decode(Meters(), 12);
console.writeln(m.n);
Wrapper<string> w = Wrapper::Of::<string>("lab");
console.writeln(w.item);
Array<int> d = mapIt([1, 2, 3], (n) => n * 2);
console.writeln(d);
12
lab
[2, 4, 6]
Checked instantiations:
Checked instantiations
use io::console;
class Named {
string name;
new Named(string n) { name = n; }
string toString() => "Named(" + name + ")";
}
class Plain { int n = 1; }
string describe<T>(T x) => x.name + " is " + "${x}";
string guarded<T>(T x) {
match (x) {
Named => { return x.name; }
else => { return "not named"; }
}
}
console.writeln(describe(Named("a")));
console.writeln(guarded(Named("b")) + ", " + guarded(Plain()));
Array<Plain> ps = [Plain()]; // a type mention demands nothing
console.writeln(ps.length());
a is Named(a)
b, not named
1
describe(Plain()) in the program above is a compile error, because Plain has neither the field name that describe reads nor the toString() its interpolation calls:
error: type 'Plain' bound to 'T' of 'describe' has no field 'name'
note: required by 'x.name' at main.lev:10
Notes
Not supported: using T::member where T is a class-level type parameter.
See also
- Type expressions — How a type is written: names, qualified names, generic instantiations, unions, optionals and function types.