Non-null objects, the Null Object pattern, and T.init
Michel Fortin
michel.fortin at michelf.ca
Sun Jan 19 16:44:21 PST 2014
On 2014-01-19 20:07:40 +0000, Timon Gehr <timon.gehr at gmx.ch> said:
> On 01/19/2014 01:03 PM, Michel Fortin wrote:
>> Actually, 'A?' would implicitly convert to 'A' where the compiler can
>> prove control flow prevents its value from being null.
>
> I think the type should be upgraded. i.e.:
>
>> So you can
>> dereference it in a branch that checked for null:
>>
>> class A { int i; void foo(); }
>> void bar(A a); // non-nullable parameter
>>
>> void test(A? a, A? a2)
>> {
>> a.i++; // error, 'a' might be null
>> a.foo(); // error, 'a' might be null
>> bar(a); // error, 'a' might be null
>>
>> if (a)
>> {
> static assert(is(typeof(a)==A));
>> a.i++; // valid [...]
>> a.foo(); // valid [...]
>> bar(a); // valid [...]
>> }
>> }
That's one way to do it. Note that this means you can't assign null to
'a' inside the 'if' branch. But I wouldn't worry too much about that. I
think it'd make a good first implementation.
What I expect from a not-null feature is that it starts by being
over-restrictive and with time, as the control flow analysis evolves,
unnecessary restrictions would be lifted. That's similar to how CTFE
and purity became what they are today.
--
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca
More information about the Digitalmars-d
mailing list