Declarations
Fields
Declare the data a class or struct holds, with optional initializers, and how a field without an initializer gets its default value.
since 0.1.0-alpha.1linuxwindowswasm
Description
A field is a named slot of data inside a class or struct:
public string label;
public distinct int value = 0;
int count = 5;
A field has a type and a name, an optional access modifier, optional modifiers (distinct, const,
readonly, weak, late) and an optional initializer. An initializer is an expression that is
evaluated each time an object is created, so every object gets its own value, including its own array.
A field or local variable declared without an initializer gets the default for its type, when the type has one:
| type | default |
|---|---|
int |
0 |
float |
0.0e0 when printed |
bool |
false |
string |
"" |
Array<T>, Map<K, V>, Set<T> |
empty |
| an enum | its first member |
T? |
None |
| a class or struct | an object made with default construction |
a type parameter T, an interface, a function type, Block |
no default |
| a class or struct whose default construction would leave one of its fields without a value | no default |
A class or struct's default construction runs its constructor that takes no arguments; without one,
it fills every field with its own default, so a field of a type without a default leaves the class
without a default too. A field whose type has no default must be given a value before anyone can
read it: an initializer, an assignment in every constructor before the constructor uses this
(lang.constructors), the late modifier (lang.late), or an optional type (T?). A local of such a
type must be assigned before it is read, and a global or static field of such a type needs an
initializer or an optional type.
Defaults and per-object initializers
use io::console;
class Inner { int n = 7; }
class Rec {
int i;
float f;
bool b;
string s;
Array<int> a;
Map<string, int> m;
Inner inner;
int? maybe;
int withInit = 5;
}
Rec r = Rec();
console.writeln(r.i);
console.writeln(r.f);
console.writeln(r.b);
console.writeln("[" + r.s + "]");
console.writeln(r.a.length());
console.writeln(r.m.length());
console.writeln(r.inner.n);
console.writeln(r.maybe);
console.writeln(r.withInit);
int local;
string sl;
console.writeln(local);
console.writeln("[" + sl + "]");
0
0.0e0
false
[]
0
0
7
None
5
0
[]
Rules
- A field declaration is
[access] [modifiers] Type name [= initializer];. - An initializer runs once for each object created, in declaration order, so a field initialized with an array literal or a call gets a fresh value for every object.
- An initializer runs before any constructor. It may read the fields that already have their values
when it runs — the class's own fields declared above it and inherited fields with a default or an
initializer — and may not otherwise use
this: no method call (this.m()or a barem()), nothisas a value or argument, no lambda that referencesthisor a member, no read of a field declared below it or of a field a constructor must assign. A callback that needsthisis alatefield assigned in the constructor. - A field with no initializer gets its type's default, as in the table above. Fields of class type are constructed with default construction.
- A field whose type has no default must be initialized, assigned by every constructor
(
lang.constructors), declaredlate(lang.late), or declared optional. A class without a constructor of its own is built memberwise, so its construction must supply every such field. - A field whose default would construct its own class again —
class Node { Node next; }, orclass A { B b; }withclass B { A a; }— is a compile error: declare it optional (Node? next;); it starts asNone. A constructor assignment does not exempt it. Alatefield never default-constructs, so it is no link of such a cycle:class Node { late Node next; }is accepted. constfixes a field to a compile-time constant (lang.const);readonlyfixes it at construction time (lang.readonly);weakmakes it a non-owning reference (lang.weak-fields);latelets it be assigned after construction (lang.late);distinctkeeps it separate from a same-named field of another base (lang.distinct).- A field redeclared along a single inheritance chain is one slot, and the more-derived declaration
wins. Two unrelated bases declaring one name and type is a compile error unless the class
restates the field or one of them is
distinct. A class holds one field per name: two bases declaring one name with different types is a compile error unless one isdistinct; seelang.multiple-inheritance.
Examples
Initializers are evaluated for each object:
Each object evaluates its initializers
use io::console;
int counter = 0;
int next() { counter += 1; return counter; }
class Item {
int id = next();
Array<string> tags = [];
string label = "item-" + counter.toString();
}
Item a = Item();
Item b = Item();
console.writeln(a.id);
console.writeln(b.id);
console.writeln(a.label);
console.writeln(b.label);
a.tags.add("x");
console.writeln(a.tags.length());
console.writeln(b.tags.length());
1
2
item-1
item-2
1
0
A link back to the same type is optional:
A self-referential field
use io::console;
class Node { int v = 1; Node? next; }
Node n = Node();
console.writeln(n.next == None);
n.next = Node();
console.writeln(n.next != None);
true
true
See also
- Classes — Declare reference types with fields, methods, constructors and accessors, with generics and inheritance from one or more base classes.
- Value structs — Declare value types that are copied on every assignment, pass and return, with derived equality and explicit mutating methods.
- distinct fields — Keep same-named fields of different bases in separate slots, reached by qualification.
- const declarations — Fix a local, field, global, parameter or loop binding after its initializer, with the exact rules for each kind of slot.
- readonly fields — Fix an instance field once, either in its initializer or in every constructor, and keep it read-only afterwards.
- weak fields — Hold a non-owning reference to an object that reads as None once the object is gone.
- late fields — Declare an instance field that gets its value after construction and raises if it is read before then.
- Constructors — Declare constructors with new, select among them by label and argument types, call base constructors, and construct classes that declare none.