Project Elvis

Steven Schveighoffer schveiguy at yahoo.com
Sun Oct 29 20:05:08 UTC 2017


On 10/29/17 12:29 PM, Ola Fosheim Grøstad wrote:
> On Sunday, 29 October 2017 at 15:57:19 UTC, Steven Schveighoffer wrote:
>> I would have expected Nullable!int to fit the bill, but unfortunately, 
>> opCast(bool) doesn't work on a null Nullable.
>>
>> But certainly you can construct a type that does work.
> 
> The right thing to do is to create a type that you cannot cast to bool, 
> but where you can test for invalid values and substitute in a default.

This is pretty simple, the if(x) provides a mechanism to check called 
"casting to bool". That doesn't mean it will shoehorn bool into the 
expression. In fact, the elvis operator provides a perfect way to type 
the result with the "common type" rules of D.

The way to do it is to make a type that checks whether the expression is 
valid or not, makes that into a bool, and then provides the real 
expression to the result.

> Forcing people to have a boolean interpretation of a type mean 
> valid/invalid state has viral consequences. It means that if the type 
> has a zero value then a boolean interpretation of zero now should give 
> true. That's not good for generic code.

It's actually perfect for generic code. If you need something other than 
the current "0 means false" behavior (like for instance int), then you 
wrap in a type that opCast!bool means what you want.

It should work just like a pointer.

In swift this is exactly what the ? operator does. I just wish Nullable 
worked this way, I'm surprised it doesn't.

-Steve


More information about the Digitalmars-d mailing list