Express "Class argument may not be null" ?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 8 11:57:48 PDT 2017


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.

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);};

Since the contract is part of the signature, this should be symantically 
what you want.

However, this has to be done on every function that would accept a 
Klass, there's no way to bake it into the type itself.

-Steve


More information about the Digitalmars-d-learn mailing list