An Optional!T signifies the intent of your code, works as a range and is therefore usable with Phobos algorithms, and allows you to call methods and operators on your types even if they are null references - i.e. safe dispatching.

Some use cases:

When you need a type that may have a value or may not (Optional!Type)

When you want to safely dispatch on types (oc(obj).someFunction // always safe)

When you want to not crash with array access (some([1, 2])[7] == none // no out of bounds exception)

When you want to perform an operation if you get a value (obj.map!doSomething.or!doSomethingElse)

Motivation for Optional

Let's take a very contrived example, and say you have a function that may return a value (that should be some integer) or not (config file, server, find operation, whatever), and then you have functions add1 and add2, that have the requirements that they may or may not produce a valid value. (maybe they do some crazy division, or they contact a server themselves to fetch a value, whatevs).

You can also replace int with Nullable!int and then instead of `if (v)` you'd have to do `if (!v.isNull)` and instead of `v you'd do v.get`.

How about ranges?

There's std.range.only:

auto add2(Range)(Range r)
if (isInputRange!Range && is(ElementType!Range == int))
// constrain to range type only and int element type?
// I need to ensure it has a length of one.
// And there's no way to ensure that in compile time without severly constraigning the type
{
// do we have one element or more now?
// what do we do if there's more than one?
// do we restrain it at run time to being there?
enforce(r.walkLength <= 1); // ??
// Should we map all of it?
return v.map!(a => a + 1);
// Or just the first?
return v.take(1).map!(a => a + 1);
// But what do I do with the rest then?
}
auto add2(Range)(Range r) if (isInputRange!Range) {
// same headache as above
}
void f() {
auto v = maybeGet();
// can we assign it to itself?
v = v.add1.add2;
// No, no idea what it returns, not really the same type
// so this...
refRange(&v).add1.add2; // ??
// no that won't work (can it?), lets create a new var
auto v2 = v.add1.add2 // and let type inference do its thing
writeln(v2); // now ok.
}

Let's try an Optional!int

FAQ

Can't I just use a pointer as an optional

Well yes, you can, but you can also stick a pencil up your nostril. It's a bad idea for the following reasons:

In order to achieve stability, you have to enforce checking for null. Which you cannot do

Null is part of the value domain of pointers. This means you can't use an optional of null

The caller doesn't know who owns the pointer returned. Is it garbage collected? If not should you deallocate it?

It says nothing about intent.

What about std.typecons.Nullable?

It is not like the Nullable type in Phobos. Nullable is basically a pointer and applies pointer semantics to value types. It does not give you any safety guarantees and says nothing about the intent of "I might not return a value". It does not have range semantics so you cannot use it with algorithms in phobos. And it treats null class objects as valid.

It does, however, tell you if something has been assigned a value or not. Albeit a bit counterintuitively, and in some cases nonsensically:

class C {}
Nullable!C a = null;
writeln(a.isNull); // prints false

With refernece types (e.g., pointers, classes, functions) you end up having to write code like this:

Scala we have a Swift comparison

Idiomatic usage of optionals in Swift do not involve treating it like a range. They use optional unwrapping to ensure safety and dispatch chaining. Scala on the other hand, treats optionals like a range and provides primitives to get at the values safely.

Like in swift, you can chain functions safely so in case they are null, nothing will happen: