interface inference

Antonio antoniocabreraperez at gmail.com
Tue Nov 28 15:15:40 UTC 2023


On Tuesday, 28 November 2023 at 14:10:30 UTC, Dom DiSc wrote:
> On Tuesday, 28 November 2023 at 11:01:14 UTC, Antonio wrote:
>> ```d
>> I aOrB(bool check){
>>   if(check)
>>     return new A();
>>   else
>>     return new B();
>> }
>> ```
>>
>> **Is it the expected behaviour for ternary conditional?**
>
> Here the compiler knows what type to return (from the function 
> signature).
> But the ternary operator doesn't know this,

Why?... ternary operators should deduce returning type the same 
way

> need to be of the same type (or implicitly convert to a common 
> type).

It is a common type: the ```I``` interface.

In fact, if you use  ```abstract class``` instead 
```interface```, it works:

```d
abstract class I { bool check(); }
class A : I { override bool check() =>true; }
class B : I { override bool check() =>false;}

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

void main()
{
   assert( aOrB(true).check );
}
```

Why ternary operator accepts covariance rules applied to base 
class, but not applied to interface?


About cast(I)... it allows "illegal" castings causing runtime 
segmentation faults if not used carefully:

```d
class X { string xname() =>"I'm x"; }
class Y { string yname() =>"I'm y"; }
void main(){
   (cast(Y) new X()).yname;  // Runtime segmentation fault
}
```

This is another good reason to avoid using cast when possible.




More information about the Digitalmars-d-learn mailing list