"if" statement

Benjamin Schaaf ben.schaaf at gmail.com
Mon Mar 25 07:12:50 UTC 2019


On Sunday, 24 March 2019 at 12:45:13 UTC, Francesco Mecca wrote:
> https://run.dlang.io/is/zRcj59
>
> ```
> alias Alg = Algebraic!(int, string);
>
> void main()
> {
> 	int n = 2;
>     Alg value;
>
>     value = n == 2 ? 2 : "string";
> }
> ```
>
> The original code used SumType but the effect is the same.
>
> I suppose that I could write the following:
>
> ```
>     if(n == 2) value = 2;
>     else value = "string";
> ```
>
> Is there a workaround for this that maintains a similar 
> syntactic structure?
> is this behaviour accepted or should the compiler translate the 
> first case in the second?

You can achieve the same thing by just constructing your 
algebraic type earlier:

   value = n == 2 ? Alg(2) : Alg("string");


More information about the Digitalmars-d-learn mailing list