The problem with Nullable: nullable(null).isNull is false.

Timon Gehr timon.gehr at gmx.ch
Mon Jul 25 12:04:35 UTC 2022


On 25.07.22 10:58, Piotr Mitana wrote:
> Hello. As Nullable has gained a bit recently (disabling automatic 
> aliasing to content andrange interface – thanks for that!), it needs one 
> more improvement.
> 
> Currently:
> 
> ```d
> assert(nullable(null).isNull == false);
> ```
> 
> It's might be very misleading – to make it truly safe, an object in 
> nullable requires a double-check:
> 
> ```d
> class C {}
> 
> // ...
> 
> Nullable!C aThing = someCode()
> 
> if(!aThing.isNull && aThing.get != null) {
>      // Now we are safe
> }
> 
> ```
> 
> The simple solution is to use the `Nullable(T, nullValue)(T t)` variant, as
> 
> ```d
> assert(nullable!null(null).isNull == true);
> ```
> 
> The solution in my opinion is:
> 
> - disable `Nullable(T)` for any type that can have `null` value,
> - for `Nullable(T, T nullValue)` add default the `nullValue` to `null` 
> for these types, so that it replaces the `Nullable(T)` usage.
> 
> I know that it changes code's behavior, so would require the deprecation 
> process probably. However, I expect the Nullable in its current form is 
> rarely used in conjunction with classes because of having this exact 
> issue. Implementing this change would allow it to be used as a proper 
> optional type that could serve to prevent null-related errors.

Not a big fan. E.g., this ad-hoc special case would make it hard to use 
Nullable reliably in generic code.


More information about the Digitalmars-d mailing list