Should "a is b" compile if a and b have unrelated classes?

Steven Schveighoffer schveiguy at yahoo.com
Tue Apr 10 23:53:20 UTC 2018


On 4/10/18 5:52 PM, Michael Coulombe wrote:
> I had a bug in my code that was messing me up for a while, and it boiled 
> down to an identity check between two Object references with unrelated 
> static types, like below:
> 
> class A {}
> class B {}
> void main() {
>      A a = new A;
>      B b = new B;
>      if (a is b) {} // compiles
> }
> 
> I was surprised that the type system failed me here. It's true that A 
> and B could be upcast to Object and then comparisons would make sense 
> type-wise, but the comparison should never pass (and the compiler should 
> know it won't since they are in separate inheritance subtrees) unless 
> the programmer is intentionally breaking the type system.
> 
> Is there reasoning for this? If not, should it be a warning or error, as 
> it is for example when comparing two pointers to structs of different 
> types?

Probably the reason is laziness. Sure it could be outlawed.

But `is` has a special connotation of "identity", meaning it's EXACTLY 
the same. Let's look at what does compile:

https://run.dlang.io/is/KHcHCc

So there is at least some type checking for `is`, when it comes to 
pointers. There's definitely a precedent for this.

The question is, should it just fold to "false", or should it fail to 
compile? If we change it to an error, there may be some unintentional 
code breakage out there.

-Steve


More information about the Digitalmars-d-learn mailing list