Final

Type constructor for final (aka head-const) variables.

Final variables cannot be directly mutated or rebound, but references reached through the variable are typed with their original mutability. It is equivalent to final variables in D1 and Java, as well as readonly variables in C#.

When T is a const or immutable type, Final aliases to T.

  1. template Final(T)
    template Final (
    T
    ) {}
  2. Final!T makeFinal(T t)

Members

Structs

Final
struct Final
Undocumented in source.

Examples

Final can be used to create class references which cannot be rebound:

static class A
{
    int i;

    this(int i) pure nothrow @nogc @safe
    {
        this.i = i;
    }
}

auto a = makeFinal(new A(42));
assert(a.i == 42);

//a = new A(24); // Reassignment is illegal,
a.i = 24; // But fields are still mutable.

assert(a.i == 24);

Final can also be used to create read-only data fields without using transitive immutability:

static class A
{
    int i;

    this(int i) pure nothrow @nogc @safe
    {
        this.i = i;
    }
}

static class B
{
    Final!A a;

    this(A a) pure nothrow @nogc @safe
    {
        this.a = a; // Construction, thus allowed.
    }
}

auto b = new B(new A(42));
assert(b.a.i == 42);

// b.a = new A(24); // Reassignment is illegal,
b.a.i = 24; // but `a` is still mutable.

assert(b.a.i == 24);
Suggestion Box / Bug Report