Keyword to avoid not null references
Adam D. Ruppe
destructionator at gmail.com
Sat Apr 21 16:01:19 PDT 2012
On Saturday, 21 April 2012 at 22:48:27 UTC, Namespace wrote:
> So every time i want to avoid null references i have to write
> "NotNull!(Foo) f" (or better, because it's a struct: "ref
> NotNull!(Foo) f")?
It is already a reference! Otherwise, it couldn't be null anyway.
But, yes, you'd write NotNull!Foo. If "NotNull" is too
long for you, you could always alias it to something else.
alias NotNull n;
n!Foo f;
whatever floats your boat.
> And therefore i must initialize them with NotNull!(Foo) f = new
> Foo();? That would be a little annoying.
If you don't initialize it, it would be null... so yes,
you have to initialize it.
> What if i needed in function bar only Foo f which can be null
> but in quatz i need a not null Reference?
If it can be null, you check for null or assume it isn't and
just pass it straight to NotNull.
One of the pull request comments suggests adding assumeNotNull
and checkNotNull to help with this. I'll add that later.
> In my opinion the best way would be to initialize them with Foo
> f = new Foo(); and if i pass them to bar, it will be implicit
> cast to NotNull!(Foo).
An implicit cast to not null would defeat the point of
the new type!
It implicitly casts to the regular (nullable) type,
but going from null to not null implicitly means you
have no help in catching it from the type system.
More information about the Digitalmars-d-learn
mailing list