On 4/2/18 5:31 AM, Timoses wrote:
On Sunday, 1 April 2018 at 15:54:16 UTC, Steven Schveighoffer wrote:
I currently have a situation where I want to have a function that accepts a parameter optionally.

I thought maybe Nullable!int might work:

void foo(Nullable!int) {}

void main()
{
   foo(1); // error
   int x;
   foo(x); // error
}


Can somebody enlighten me what this topic is about?

I thought an optional parameter would be as easy as

     void foo(int i = 0) { writeln(i); }

     void main()
     {
         int x;
         foo(x);
         foo(1);
         foo();
     }

Is the Nullable!int approach because 'i' would always "optionally" be 0 if not passed with above 'foo'?

I'm talking about optionals as they are in other languages, such as Swift: https://en.wikipedia.org/wiki/Option_type

In other words, there is a distinct state of "not provided" from the other values it might take.

Nullable works to fill this purpose, but I didn't realize that I'd have to wrap all calls to it. I was hoping for something more like Swift's option types. In Swift, I would do:

function foo(x: Int?)

And I can check x to see if it's nil inside the function. I can just call foo with a plain Int and it works fine. Int implicitly casts to Int?, but Int? needs an explicit conversion to Int. That was the relationship I was looking for. Apparently, not attainable in D, unless you do it on initialization.

-Steve

Reply via email to