LEVIATHAN vd52e79c4 · d52e79c486

Declarations

Static members

Class-level methods and fields, reached with '::' and shared by every instance.

since 0.1.0-alpha.1linuxwindowswasm

Description

A member declared static belongs to its class, not to an instance. A class or struct can declare static methods, static fields and static const fields. A static method has no this; a static field is one variable for the whole program, shared by every instance of the class.

class Color {
    static int created = 0;              // one variable per class
    static const int Max = 255;          // a constant, fixed by its initializer
    static Color? Parse(string hex) { ... }   // no `this`
}

Outside the class, a static is reached through the class name with ::: Color::created, Color::Parse("#fff"). The class name with . is the same access: Color.created, Color.created = 1, Color.items[0] = 2 and Color.Parse(s) are rewritten to the :: form, as . through an instance is (below). Inside the class body — in an instance method, a constructor, another static member or a field initializer — it is reached by its bare name.

Static methods and fields

use io::console;

class Color {
    int r; int g; int b;
    static int created = 0;
    static const int Max = 255;
    new Color(int r, int g, int b) {
        this.r = r; this.g = g; this.b = b;
        created += 1;
    }
    static Color? Parse(string hex) {
        if (hex.length() != 7) return None;
        return Color(255, 136, 0);
    }
    static string Pad(int c) => c < 10 ? "0" + c.toString() : c.toString();
    string describe() => "rgb " + Pad(r) + " " + Pad(g) + " " + Pad(b);
}
void main() {
    Color? c = Color::Parse("#ff8800");
    if (c != None) { console.writeln(c.describe()); }
    console.writeln(Color::Parse("nope") == None);
    Color k = Color(1, 2, 3);
    console.writeln(Color::created);
    Color::created += 10;
    console.writeln(Color::created);
    console.writeln(Color::Max);
}
main();
rgb 255 136 00
true
2
12
255

Rules

  • static may be written on a method or a field of a class or struct, together with public or private, const, attributes and the member's own generic parameters. static on a top-level or namespace declaration, a local variable or a parameter is a compile error ("'static' applies to members of a class or struct"), and so is a static member of an interface.
  • A constructor, an operator and an accessor with a selector or extra parameters cannot be static. override, mutating, distinct and weak cannot be combined with static. static readonly is a compile error: write static const.
  • A static method has no this. Using this, or an instance member by its bare name, inside a static member is a compile error ("'n' is an instance member of 'C'; a static member has no 'this'").
  • A name is either static or an instance member of a class, never both: a static and an instance member with the same name is a compile error, and so is a static field and a static method with the same name. A static may not share its name with a constructor label, nor with the class's own name.
  • Inside a class body a bare name is looked up as a local variable, then an instance member of the class, then a static member of the class, then a global.
  • Type::name names a static of Type. A name that is neither a constructor label nor a static is a compile error ("type 'C' has no static member 'b'", "type 'C' has no constructor or static method 'b'"). Static methods and constructor labels share the Type::name(args) call form; they never share a name.
  • A static method referenced without a call (var f = Color::Parse;) is an ordinary function value with no receiver.
  • A static field is a global variable: it is default-initialized with every other global, then its initializer runs in the namespace phase of the program (lang.const, "Initialization order of globals"), in source order with namespace-level variables — each class at its own position, its static fields in declaration order. A static initializer may read a namespace variable or another class's static declared earlier. Every top-level initializer and statement sees every static initialized.
  • A static const field is fixed by its initializer, which may be computed at run time; any later write is a compile error. A static const with a constant initializer can be read by comptime code.
  • A static is not part of an instance: memberwise construction, a struct's derived (==), a @repr("C") layout and meta::Class.fields/methods all ignore it.

Static properties

static T get N() and static set N(T v) declare a property of the class, read and written as Type::N (or N inside the class, or through an instance). A static field of the same name is the property's backing field; a getter with no declared type views it and has its type.

getter setter backing field a read of N a write N = v
yes yes either the getter the setter
yes no yes the getter the field, directly
yes no no the getter compile error: "'N' is a read-only static property"
no yes yes the field, directly the setter
no yes no compile error: "'N' is a write-only static property" the setter
  • Compound assignment (Type::N += 1) reads by the table, then writes by the table.
  • Inside the bodies of N's own accessors, N and Type::N name the backing static field, with no getter or setter call. With no backing field, naming it there is a compile error ("'N' has no backing static field; inside its own accessors 'N' names that field").
  • An assignment through a setter has the assigned value, as an assignment to a field does.
  • A static property is never a function value: var n = Type::N; reads it.
  • Hiding is by name: a class that declares only static set N hides a base's static get N too.

A static property with a backing field

use io::console;

class Counter {
    static int count = 0;
    static int get count() => count;
    static set count(int v) { count = v < 0 ? 0 : v; }
    static string get Label() => "n=" + count.toString();
}
void main() {
    Counter::count = -5;
    console.writeln(Counter::count);
    Counter::count = 4;
    Counter::count += 3;
    console.writeln(Counter::Label);
    int assigned = (Counter::count = -1);
    console.writeln(assigned);
    console.writeln(Counter::count);
}
main();
0
n=7
-1
0

A get-only property over a backing field writes the field; a set-only one reads it:

Get-only and set-only static properties

use io::console;

class Gauge {
    static int level = 7;
    static int get level() => level * 10;
    static int raw = 1;
    static set raw(int v) { raw = v + 100; }
}
void main() {
    console.writeln(Gauge::level);
    Gauge::level = 2;
    console.writeln(Gauge::level);
    Gauge::raw = 5;
    console.writeln(Gauge::raw);
}
main();
70
20
105

Inheritance and hiding

A class sees its bases' statics: Derived::name, and a bare name in Derived's bodies, reach a static declared by a base class. If Derived declares any static of that name, it hides every base static of the name — a whole overload set, so a base-only overload is not reachable through Derived — and the compiler warns ("static 'Derived::f' hides static 'Base::f'"). Base::name always reaches the base's own. Statics are never dispatched on an instance's class: a base's body that names a static gets the base's.

  • R1 holds across the hierarchy: a static and an instance member of one name in a class and its bases is a compile error ("'n' in 'D' clashes with the instance member 'B::n'"), and so is a constructor label that matches an inherited static.
  • With multiple inheritance, one static reached on two paths (a diamond over the class that declares it) is one static. Two bases that bring different statics of one name make the name ambiguous where it is used: "'f' is a static of both 'A' and 'B'; write 'A::f' or 'B::f'". Statics take no part in slot composition (lang.multiple-inheritance).

Inherited statics

use io::console;

class Base {
    static int count = 0;
    static string Name() => "base";
    static int Bump() { count += 1; return count; }
}
class Derived : Base {
    string mine() => Name() + " " + Bump().toString();
}
class Left : Base { }
class Right : Base { }
class Both : Left, Right { }
void main() {
    console.writeln(Derived::Name());
    console.writeln(Derived().mine());
    Both::count += 10;
    console.writeln(Base::count);
}
main();
base
base 1
11

Declaring static string Name() => "derived"; in Derived would hide Base::Name there — Derived::Name() and a bare Name() in Derived would call the new one, Base::Name() still the base's — and the compiler would say so:

warning: static 'Derived::Name' hides static 'Base::Name'

Generic classes

A static field of a generic class is one variable for the class, shared by every instantiation, and a static is spelled with the bare class name: Box::count. Writing type arguments on the qualifier is a compile error ("static members of a generic class are shared by every instantiation; write 'Box::count'"). A static member cannot mention the class's own type parameters — not in its signature, its body or a T::member — because it has no instance to bind them ("'T' is a class-level type parameter; a static member has no instance to bind it"). A static method may declare type parameters of its own, inferred from the arguments or given with the turbofish.

Statics of a generic class

use io::console;

class Box<T> {
    T value;
    static int made = 0;
    new mk(T x) { value = x; made += 1; }
    static U Pick<U>(U a, U b) => a;
}
void main() {
    Box<int> a = Box::mk::<int>(1);
    Box<string> b = Box::mk::<string>("s");
    console.writeln(Box::made);
    console.writeln(Box::Pick(3, 4));
    console.writeln(Box::Pick::<string>("x", "y"));
}
main();
2
3
x

Inside a generic function, T::name reaches the static of the type the function is instantiated with (lang.generics):

T::name on a static

use io::console;

class Celsius {
    float deg;
    static Celsius Parse(string s) => Celsius(s.toFloat() ?? 0.0);
    string describe() => deg.toString() + " C";
}
string show<T>(string s) => T::Parse(s).describe();
console.writeln(show::<Celsius>("21.5"));
2.15e1 C

Through an instance

A static may also be reached through an instance of its class — c.created, c.Parse(s), this.Format(x) — when the instance is written as a plain path: a variable, a parameter, this, or a chain of . field reads over one (a.b.c). The compiler rewrites it to Type::name, so the instance is not evaluated. Any other receiver — a call, an index, ?., a parenthesized expression — is a compile error ("'n' is static; reach it through a plain path, as in 'C::n'").

A static through an instance

use io::console;

class Counter {
    static int total = 0;
    static int Add(int n) { total += n; return total; }
    int addTwice(int n) => this.Add(n) + Add(n);
}
void main() {
    Counter c = Counter();
    c.total = 5;
    console.writeln(c.Add(1));
    console.writeln(c.addTwice(2));
    console.writeln(Counter::total);
}
main();
6
18
10

Foreign functions and reflection

A static method may be @extern (its body is ;) or @export; a static @export uses the method's bare name as its C symbol unless symbol is given (lang.ffi). An instance method cannot be either.

Rules and macros see a class's statics in their own lists: meta::Class.fields and .methods hold the instance members, .staticFields and .staticMethods the static ones, and isStatic tells them apart (lang.splices). A trident project's entry may name a static method: entry = "Main::Run" (trident.manifest).

Examples

A static field keeps state that every instance shares; a struct's statics are shared by every copy:

One field per class

use io::console;

struct Ticket {
    int id;
    static int next = 1;
    static Ticket Issue() {
        Ticket t = Ticket(next);
        next += 1;
        return t;
    }
}
void main() {
    Ticket a = Ticket::Issue();
    Ticket b = Ticket::Issue();
    Ticket copy = b;
    console.writeln(a.id);
    console.writeln(copy.id);
    console.writeln(Ticket::next);
}
main();
1
2
3

Static fields initialize in the namespace phase, in source order, before any top-level code:

Initialization order

use io::console;

namespace Defaults {
    int port = 8000;
}
class Server {
    static int basePort = Defaults::port + 80;
    static Array<string> names = ["main"];
}
int first = Server::basePort;
console.writeln(first);
console.writeln(Server::names.length());
8080
1

A static helper used from instance methods, and a static method as a function value:

Static helpers and function values

use io::console;

class Temperature {
    float celsius;
    new Temperature(float c) { celsius = c; }
    static float ToFahrenheit(float c) => c * 9.0 / 5.0 + 32.0;
    float fahrenheit() => ToFahrenheit(celsius);
}
float apply((float) => float f, float x) => f(x);
void main() {
    console.writeln(Temperature(100.0).fahrenheit());
    var convert = Temperature::ToFahrenheit;
    console.writeln(convert(0.0));
    console.writeln(apply(Temperature::ToFahrenheit, 37.0));
}
main();
2.12e2
3.2e1
9.86e1

Errors a static member reports:

error: 'this' is not available in a static member
error: 'n' is an instance member of 'C'; a static member has no 'this'
error: type 'C' has no static member 'b'
error: 'n' is declared both static and non-static in 'C'

Notes

A static belongs to the class that declares it. Write Type::name from outside the class; a bare name inside the class body.

A static field is shared program state, exactly like a top-level variable, including across threads (lang.threads).

private and protected on a static are enforced as on every other member (lang.access): a private static is reachable only inside its class, a protected one inside its class and every class derived from it.

See also

  • Classes — Declare reference types with fields, methods, constructors and accessors, with generics and inheritance from one or more base classes.
  • Constructors — Declare constructors with new, select among them by label and argument types, call base constructors, and construct classes that declare none.
  • const declarations — Fix a local, field, global, parameter or loop binding after its initializer, with the exact rules for each kind of slot.
  • Member access and qualification — The dot for instances, the double colon for base, static and namespace names, optional chaining, and the explicit-type marker.
  • Method references — Naming a function, method or labeled constructor without calling it yields an ordinary function value.