Null references

Nick Treleaven nospam at example.net
Tue Aug 21 13:17:08 PDT 2012


On 21/08/2012 14:30, Simen Kjaeraas wrote:
> On Tue, 21 Aug 2012 13:55:58 +0200, Regan Heath <regan at netmail.co.nz>
> wrote:
>
>> I don't buy the argument that having to explicitly type ".get" will
>> stop anyone from automatically coding statements like:
>>
>> val g: Option[T] = f.doSomething()
>> g.get.doSomethingElse()
>
> So don't give them that access?

Yes, or force conversion of the Option, handling the invalid case:

g.valueOrElse(null).doSomethingElse();

The above being explicit that null might be returned. The code is no 
safer, but it is much clearer. Also sometimes the caller has a better 
alternative value than null to use which is actually valid.

> I have an Option struct on my home computer that only allows access to
> the held value if the error case is simultaneously handled:
>
> Option!int a = foo();
>
> int n = a.match!(
>      (int x) => x,
>      (None n) => 0 // or throw, or what have you.
>      );
>
> The same solution is perfectly adaptable to MaybeNull, MaybeNan, and
> probably
> a host of others of the same family.
>
> With some clever use of opDispatch, one could write an Option struct that
> lets you call methods and acces members of the wrapped type, and return
> Option!ReturnType.

Apart from the opDispatch bit, I've been slowly working on something 
similar (Boost license):

https://github.com/ntrel/d-maybe/blob/master/maybe.d

I'm still working on it, but the basic ideas are there. I think the best 
bit is apply(), which supports passing multiple Maybe values, calling 
the delegate only if all Maybes are valid. In fact Maybe.map() is 
unnecessary due to apply().

Nick


More information about the Digitalmars-d mailing list