Hi

See: https://optional.dub.pm

I've totally revamped the Optional type and am now quite happy with. It has a range interface and safe dispatching and can be used to 1) avoid null dereferencing, 2) have non-null guarantees, and 3) show clear intent where there may or may not be a value. It's also @nogc and @safe and mutation of the original object during safe dispatching works as well.

Some code examples:

===
import optional;
import std.stdio: writeln;

class Residence {
    auto numberOfRooms = 4;
}
class Person {
    Optional!Residence residence;
}

auto john = some(new Person());

john.dispatch.residence.dispatch.numberOfRooms.writeln; // safe, prints "[]"
john.dispatch.residence = new Residence();
john.dispatch.residence.dispatch.numberOfRooms.writeln; // prints "[4]"

if (auto res = john.dispatch.residence.unwrap) {
    writeln(res.numberOfRooms); // safe, prints "4"
}
===

And since it's a range type as well, you can use it with phobos algos (and it provides some primitives found in e.g. scala)

===
import std.algorithm: each;

// Make a function that may or may not parse a string to an int
Optional!int toInt(string str) {
    import std.conv: to;
    scope(failure) return no!int;
    return some(str.to!int);
}

auto x = toInt("1").orElse(0);

toInt("1").each!writeln;

toInt("1").match!(
    (i) => writeln(i),
    () => writeln("nothing there"),
);
===

The readme contains a lot more details.

Some things that are on me list that I need to think about
- Consider a short form for "dispatch". Purely for convenience:
   e.g.: john.d.residence.d.numberOfRooms;
- Consider an auto dispatch (".autoDispatch"?), so that once you start a chain you don't need to write "dispatch again:
   e.g.: john.autoDispatch.residence.numberOfRooms;


Some reasonings for design:
- The dispatcher is a completely separate type because Optional is a range type and has it's own functions that would be impossible to call on a type T without unwrapping first. - The "safe dispatcher" proxy contains NO functions so that it will never trample over a type T.


Cheers,
- Ali

Reply via email to