Nullable

Defines a value paired with a distinctive "null" state that denotes the absence of a value. If default constructed, a Nullable!T object starts in the null state. Assigning it renders it non-null. Calling nullify can nullify it again.

Practically Nullable!T stores a T and a bool.

Constructors

this
this(T value)

Constructor initializing this with value.

Destructor

A destructor is present on this object, but not explicitly documented in the source.

Alias This

get_

Implicitly converts to T. this must not be in the null state. This feature is deprecated and will be removed after 2.096.

Members

Functions

nullify
void nullify()

Forces this to the null state.

opAssign
void opAssign(T value)

Assigns value to the internally-held state. If the assignment succeeds, this becomes non-null.

opEquals
bool opEquals(const(typeof(this)) rhs)
bool opEquals(const(U) rhs)

If they are both null, then they are equal. If one is null and the other is not, then they are not equal. If they are both non-null, then they are equal if their values are equal.

toString
string toString()
void toString(W writer, FormatSpec!char fmt)

Gives the string "Nullable.null" if isNull is true. Otherwise, the result is equivalent to calling std.format.formattedWrite on the underlying value.

Properties

get
inout(T) get [@property getter]
inout(T) get [@property setter]
inout(U) get [@property setter]

Gets the value if not null. If this is in the null state, and the optional parameter fallback was provided, it will be returned. Without fallback, calling get with a null state is invalid.

isNull
bool isNull [@property getter]

Check if this is in the null state.

Examples

1 struct CustomerRecord
2 {
3     string name;
4     string address;
5     int customerNum;
6 }
7 
8 Nullable!CustomerRecord getByName(string name)
9 {
10     //A bunch of hairy stuff
11 
12     return Nullable!CustomerRecord.init;
13 }
14 
15 auto queryResult = getByName("Doe, John");
16 if (!queryResult.isNull)
17 {
18     //Process Mr. Doe's customer record
19     auto address = queryResult.get.address;
20     auto customerNum = queryResult.get.customerNum;
21 
22     //Do some things with this customer's info
23 }
24 else
25 {
26     //Add the customer to the database
27 }
import std.exception : assertThrown;

auto a = 42.nullable;
assert(!a.isNull);
assert(a.get == 42);

a.nullify();
assert(a.isNull);
assertThrown!Throwable(a.get);

Meta

Suggestion Box / Bug Report