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

Piotr Mitana piotr.mitana at e.email
Mon Jul 25 08:58:08 UTC 2022


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.


More information about the Digitalmars-d mailing list