Introducing Nullable Reference Types in C#. Is there hope for D, too?
Atila Neves
atila.neves at gmail.com
Mon Nov 20 10:07:08 UTC 2017
On Sunday, 19 November 2017 at 04:04:04 UTC, Walter Bright wrote:
> On 11/18/2017 6:25 PM, Timon Gehr wrote:
>> I.e., baseClass should have type Nullable!ClassDeclaration.
>> This does not in any form imply that ClassDeclaration itself
>> needs to have a null value.
>
> Converting back and forth between the two types doesn't sound
> appealing.
Converting isn't necessary - one can instead map over nullable
types, with the mapped function not actually being called when it
is indeed null. i.e.
struct Nullable(T) {
//...
auto map(alias F)() {
return isNull
? ReturnType!F.init
: F(_value);
}
}
>>> What should the default initializer for a type do?
There shouldn't be one - any usage of a non-nullable type that
hasn't been initialised should be a compile-time error. Similar
to using a non-initialised reference in C++, but relaxed to allow
assignment at a place other than the declaration.
> Interestingly, `int` isn't nullable, and we routinely use
> rather ugly hacks to fake it being nullable, like reserving a
> bit pattern like 0, -1 or 0xDEADBEEF and calling it
> INVALID_VALUE, or carrying around some other separate flag that
> says if it is valid or not. These are often rich sources of
> bugs.
Nullable!int.
> As you can guess, I happen to like null, because there are no
> hidden bugs from pretending it is a valid value - you get an
> immediate program halt - rather than subtly corrupted results.
The problem with null as seen in C++/Java/D is that it's a
magical value that different types may have. It breaks the type
system.
> Yes, my own code has produced seg faults from erroneously
> assuming a value was not null. But it wouldn't have been better
> with non-nullable types, since the logic error would have been
> hidden and may have been much, much harder to recognize and
> track down.
No, it would have been a compile-time error instead.
Atila
More information about the Digitalmars-d
mailing list