Nullable condition operator
rumbu via Digitalmars-d
digitalmars-d at puremagic.com
Mon Dec 14 07:34:35 PST 2015
On Monday, 14 December 2015 at 13:19:13 UTC, Martin6265 wrote:
> I dont said C# is better, just missing some preferred stuffs
> from other languages.
> `.?` from C# is same thing as message passing in ObjC. (You can
> send message to invalid object without accessing null pointer).
> And I miss that stuff in D.
>
> Maybe will create a new instance of T if T is null, right?
>
> class Responder {
> Responder m_parent;
>
>
> void SetSomething(int a) {
> m_parent.maybe.SetSomething(a);
> }
> }
>
> So, this example will ends in infinite loop.
> But I don't want to call SetSomething on m_parent if m_parent
> is null.
Despite the enthusiasm in the aforementioned topic and despite
the obsession that "every other language feature can be
transformed in a D library solution beacuse D is so powerful",
the D monad-like implementation is incomplete and is not
equivalent to the C# ? operator, it wrongly assumes a field as a
result type. Compiling your example, will result in an error
message - "no field SetSomething for Maybe" (or similar).
The D implementation will not create a new instance - it checks
for typeof(null) - it will return
typeof(Responder.SetSomething).init if SetSomething would be a
field (which is not).
My advice is to stick to conditional code for now, not every
other language feature can be translated.
A single suggestion your example code:
> auto var = cast(FooBar)variable;
> if (var !is null)
> var.callMethod();
can be written as:
if (auto var = cast(Foobar)) var.callMethod();
More information about the Digitalmars-d
mailing list