Nullable with reference types
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jun 30 08:16:57 PDT 2015
On Tuesday, 30 June 2015 at 00:02:38 UTC, Meta wrote:
> On Monday, 29 June 2015 at 19:29:37 UTC, sigod wrote:
>> Hi, everyone.
>>
>> ```
>> import std.typecons : Nullable;
>>
>> class Test {}
>>
>> Nullable!Test test;
>> assert(test.isNull);
>> ```
>>
>> Why does `Nullable` allowed to be used with reference types
>> (e.g. classes)?
>>
>> P.S. I have experience with C#, where `Nullable<T>` cannot be
>> used with reference types. And it sounds logical to me.
>
> It's a design mistake in Nullable. I would suggest that either
> never use Nullable with a type that already has a null value,
> or use the "overload" of Nullable that takes a null value, and
> set it to null. Example:
>
> Class Test {}
> alias NullableTest = Nullable!(Test, null);
I tend to think that it's incredibly stupid to use something like
Nullable for a type that's already Nullable. It's just silly. If
a type is already nullable, then just use that and stop being
adding extra overhead for no good reason. However, it _is_ true
that if you need to have a nullable variable in generic code
where the type that you need to be nullable could be any type,
then having Nullable work with all types - and work with them all
in the same way - is useful. Without that, you'd have to special
case your code for types which were naturally nullable (and thus
used null) and those which required Nullable. So, I can see why
it could be useful to have Nullable work with classes, but I also
question how common such a use case is.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list