Adding the ?. operator to D

Seb seb at wilzba.ch
Thu Sep 17 11:23:52 UTC 2020


On Thursday, 17 September 2020 at 00:09:43 UTC, Paul Backus wrote:
> On Wednesday, 16 September 2020 at 19:01:28 UTC, Jacob Carlborg 
> wrote:
>>
>> I would like that. It should work for an Optional/Nullable 
>> type as well. It's a good idea to add an `??` operator at the 
>> same time as well:
>>
>> auto a = A ?? B;
>>
>> if `A` is not null, assign `A` to `a`. Otherwise assign `B` to 
>> `a`.
>
> Last time this was discussed, someone posted the following 
> library version:
>
> T orElse(T)(T value, lazy T alternative)
> {
>     return value ? value : alternative;
> }
>
> auto a = A.orElse(B);

`orElse` was also proposed for Phobos, but it was intended for 
ranges.
It could be combined though:

```
myClassInstance.orElse(otherClassInstance); // class
"".orElse("fallback"); // ranges
Nullable!int nInt;
nInt.orElse(42); // nullable
```


More information about the Digitalmars-d mailing list