Non-null objects, the Null Object pattern, and T.init

Peter Alexander peter.alexander.au at gmail.com
Thu Jan 16 18:02:05 PST 2014


On Friday, 17 January 2014 at 01:42:38 UTC, Andrei Alexandrescu 
wrote:
> Whenever a Widget is to be default-initialized, it will point 
> to Widget.init (i.e. it won't be null). This beautifully 
> extends the language because currently (with no init 
> definition) Widget.init is null.

Hmm, what about derived classes? How do you check for a valid 
Widget given a DerivedWidget.init?

class DerivedWidget : Widget
{
     static DerivedWidget init = new DerivedWidget(...);
}

bool valid(Widget w) { return w !is Widget.init; }

DerivedWidget foo;
assert(!valid(foo)); // doesn't fire, foo is valid?


The nice thing about null is that it is the bottom type, so it is 
a universal sentinel value.

Also, what about interfaces? You cannot define an init for an 
interface. Obviously that could just be a known and accepted 
limitation of this proposal, but I'm not a huge fan of solutions 
that only work in a subset of situations. Perhaps there is a 
solution that I haven't thought of.


> assert(x == 42 && parent is Widget.init);

Is that meant to say "x is Widget.init"?


More information about the Digitalmars-d mailing list