Null-Coalescing Operator and Extensions

Simen Kjærås simen.kjaras at gmail.com
Mon Aug 27 07:59:17 UTC 2018


On Saturday, 25 August 2018 at 19:16:26 UTC, Jacob Carlborg wrote:
> On 2018-08-25 15:33, SG wrote:
>> Hi,
>> 
>> 1) I program in C# and I'm wondering if there is something 
>> like ?? (Null-Coalescing Operator) in D? (I remember some 
>> proposals in the past).
>
> Not in the language but it can be implemented as a library 
> function by overloading "opDispatch". See [1] for an example.
>
> [1] 
> https://github.com/jacob-carlborg/dlp/blob/9d524e282803070022848c01cf6cd25a61025004/source/dlp/core/optional.d#L228-L238

That's the null propagation operator (?.). What SG asked for is 
the null-coalescing operator (??). Of course, this can also be 
implemented in D (albeit with a slight more horrible syntax):

struct NullCoalesce {
     static auto opBinaryRight(string op : "|", T)(T lhs) {
         return NullCoalesceImpl!T(lhs);
     }
}

alias NullCoalesce _;

struct NullCoalesceImpl(T) {
     T value;
     auto opBinary(string op = "|", R)(lazy R rhs) {
         if (value is null) return rhs;
         return value;
     }
}

unittest {
     int* a = null;
     int b = 3;
     assert(*(a |_| &b) == 3);
}

--
   Simen


More information about the Digitalmars-d-learn mailing list