On Tuesday, 8 August 2017 at 18:57:48 UTC, Steven Schveighoffer wrote:
On 8/8/17 2:34 PM, Johan Engelen wrote:
Hi all,
How would you express the function interface intent that a reference to a class may not be null? For a function "void foo(Klass)", calling "foo(null)" is valid. How do I express that that is invalid? (let's leave erroring with a compile error aside for now)

There isn't a way to do this in the type itself.

One can always create a null class instance via:

MyObj obj;

There is no way to disallow this somehow in the definition of MyObj. With structs, you can @disable this(), and it's still possible but harder to do so.

Ok thanks, so this could be a reason for not being allowed to express the non-null-ness. (I still haven't found peace with the absence of an explicit * for classes)

I would say, however, that if you wanted to express the *intent*, even without a compile-time error, you could use a contract:

void foo(Klass k) in {assert(k !is null);};

Thanks. I regret leaving compile-time errors out, because in that case adding it to the function documentation would suffice.

(Btw: "Error: function foo in and out contracts require function body". But who uses .di files anyway. ;-)


Reply via email to