Nullable!T with T of class type

aliak something at something.com
Thu Jun 28 19:58:22 UTC 2018


On Thursday, 28 June 2018 at 18:10:07 UTC, kdevel wrote:
> On Tuesday, 26 June 2018 at 21:54:49 UTC, Jonathan M Davis 
> wrote:
>> [H]onestly, I don't understand why folks keep trying to put 
>> nullable types in Nullable in non-generic code.
>
> How do you signify that a struct member of class type is 
> optional?

So there're no optional type in D (ala Swift, Kotlin, Scala, 
etc).  There are a number of workarounds you can use to achieve 
the same type of behavior.

You can use ranges to denote "some" value or no value (empty 
range). But it's a bit inconvenient and the APIs to get that 
running say nothing about intent.

You can create a lightweight Maybe type: 
https://stackoverflow.com/questions/27241908/maybe-types-in-d

I've implemented an optional type as well that includes safe 
dispatching, but it's not @nogc right now -> 
https://github.com/aliak00/optional

I think there's another optional type on dub somewhere as well.

But using Nullable!T just defers the problem that optional solves:

if (nullable.isNull) {
   nullable.get.doSomething();
}

vs:

if (ptr !is null) {
   ptr.doSomething();
}

meh...

It's more of a tool to allow you to give any type nullability 
semantics.

Cheers,
- Ali


More information about the Digitalmars-d-learn mailing list