Is Nullable supposed to provide Optional semantics?

Chris Paulson-Ellis chris at edesix.com
Fri Dec 29 20:52:51 UTC 2017


I've been bitten by trying to use Nullable(T) on class types. 
Minimal example...

import std.typecons : Nullable;

void main()
{
     auto o = new Object();
     o.toString();

     Nullable!Object n = o;
     o.toString();

     n.nullify();
     o.toString(); // SegV!
}

The SEGV is caused by nullify calling object.destroy() on o, 
invalidating it. This makes Nullable unsafe to use with class 
types when there may be other references to the optional values 
in the program.

Perhaps I'm not using the correct abstraction. I'm looking for 
something equivalent to java.util.Optional, or Haskell's Maybe.

If Nullable(T) *is* intended to be used like Java Optional, then 
calling .destroy when clearing the value seems to be going beyond 
its remit for class types.

For those confused as to why you'd want to wrap a Nullable around 
something that already has nullable semantics, it's mostly about 
making APIs that explicitly declare their optional return values. 
See: 
http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html

I also want to use it in template code that works with both value 
& reference types.

Chris.


More information about the Digitalmars-d-learn mailing list