On Friday, 20 October 2017 at 04:26:24 UTC, Jonathan M Davis
wrote:
On Friday, October 20, 2017 02:20:31 Adam D. Ruppe via
Digitalmars-d wrote:
On Friday, 20 October 2017 at 00:26:19 UTC, bauss wrote:
> return foo ? foo : null;
>
> where
>
> return foo ?? null; would be so much easier.
return getOr(foo, null);
That's really easy to do generically with a function. I
wouldn't object to the ?? syntax, but if it really is
something you write all over the place, you could just write
the function.
> return foo ? foo.bar ? foo.bar.baz ? foo.bar.baz.something :
> null;
>
> Which could just be:
>
> return foo?.bar?.baz?.something;
In dom.d, since I use this kind of thing somewhat frequently,
I wrote a function called `optionSelector` which returns a
wrapper type that is never null on the outside, but propagates
null through the members. So you can do
foo.optionSelector("x").whatever.you.want.all.the.way.down
and it handles null automatically.
You can do that semi-generically too with a function if it is
something you use really frequently.
For better or worse, solutions like this are the main reason
that a number of things folks ask for don't get added to the
language. It's frequently the case that what someone wants to
do can already be done using the language as-is; it just may
not be as syntactically pleasing as what the person wants, and
they may not know D well enough yet to have come up with the
solution on their own.
- Jonathan M Davis
Yeah, but if it can be done by stuff like you said it's not
reason to not implement syntactic sugar for it.
array[0 .. 42] can be substituted by array.slice(0, 42) too, but
it's not.
it's more handy to write
void foo(int? a, string? b);
than
void foo(Maybe!int a, Maybe!string b);
same for
return a ?? null;
than
return getOr(a, null);
foo.optionSelector("x").whatever.you.want.all.the.way.down
it's not clear if you are able or not to able to hit the null.
foo?.x?.whatever?.you?.want;
is more clear and doesn't need any boilerplate.
it doesn't need to be implemented in code.