View source code
Display the source code in std/experimental/typecons.d from which this
page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a
Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Function std.experimental.typecons.makeFinal
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
.
Example
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));
writeln(a .i); // 42
//a = new A(24); // Reassignment is illegal,
a .i = 24; // But fields are still mutable.
writeln(a .i); // 24
Example
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));
writeln(b .a .i); // 42
// b.a = new A(24); // Reassignment is illegal,
b .a .i = 24; // but `a` is still mutable.
writeln(b .a .i); // 24
Authors
Andrei Alexandrescu, Bartosz Milewski, Don Clugston, Shin Fujishiro, Kenji Hara
License
Copyright © 1999-2022 by the D Language Foundation | Page generated by ddox.