interface inference

Antonio antoniocabreraperez at gmail.com
Tue Nov 28 11:01:14 UTC 2023


On Thursday, 23 November 2023 at 19:17:20 UTC, Antonio wrote:
> ```d
> interface I {
>         bool check();
> }
> class A : I {
>         bool check() =>true;
> }
> class B : I {
>         bool check() =>false;
> }
>
> I aOrB(bool check) => check ? new A() : new B();
>
> void main()
> {
>   assert( aOrB(true).check );
> }
> ```
>
> Compiler error:
>
> ```d
> x.d(11): Error: cannot implicitly convert expression `check ? 
> new A : new B` of type `object.Object` to `x.I`
> ```


I'm forced to explicitly write the cast this way

```d
I aOrB(bool check) => check ? cast(I) new A() : cast(I) new B();
```

But it is not necessary when I write same code using 
if/else/return statements

```d
I aOrB(bool check){
   if(check)
     return new A();
   else
     return new B();
}
```


**Is it the expected behaviour for ternary conditional?**




More information about the Digitalmars-d-learn mailing list