Submission: switch (...) instanceof feature

Reinier Zwitserloot reinier at zwitserloot.com
Mon May 4 03:29:47 PDT 2009


overloading methods that have overlapping types is ugly code you  
should refactor, but, you're right. We've moved from 'clearly broken'  
code to merely 'ugly, at least by most standards'. Excellent find, Remi.

How about changing to: The type of 'x' is both its original type and  
the type you've instanceof-ed on?

This way, your example would produce a compiler error: Call ambiguous,  
with suggestions to cast the x to either String or Object explicitly,  
which I think is the proper response, because of the confusion around  
the non-dynamic nature of overloading with overlapping types.

Is there a precedent for such a type concept in javac? This isn't  
quite the same as either the generics type in e.g. List<Comparable &  
Serializable> (particularly because X & Y, where Y is a strict subtype  
of X, just reduces to Y), nor the typing produced by e.g. the  
expression (foo ? new A() : new B()) (the intersection of A and B),  
which also isn't what we're looking for.



  --Reinier Zwitserloot



On May 4, 2009, at 12:18, Rémi Forax wrote:

> Reinier Zwitserloot a écrit :
>> Why is this neccessary? We have a similar situation here as the   
>> inherited exception issue: Rare and definitely broken (at runtime)   
>> code will now break at compile time. This is technically  
>> 'backwards  incompatible', insofar that code that used to compile  
>> no longer does.  However, I believe the decision was made that this  
>> technical  incompatibility was acceptable, because the code made no  
>> runtime sense  in the first place. You have the same situation here:
>>
>>
>> old code:
>>
>> Object x = foo();
>>
>> if ( x instanceof String ) {
>>   Integer y = (Integer)x;
>> }
>>
>> would compile, eventhough it's clearly bogus. With this change:
>>
>> if ( x instanceof String ) {
>>    //within this block, 'x' is considered to be both a String and   
>> whatever x's actual type is, if it's not a strict supertype of  
>> String.
>> }
>>
>
> This change is not backward compatible ...
>
> class A {
> void m(String) { ... }
> void m(Object o) { ... }
>
> void f() {
>   Object x = foo();
>   if ( x instanceof String ) {
>     m(x);      <--  call m(Object), will call m(String)
>  }
> }
> }
>
> [ ... ]
>
>>  --Reinier Zwitserloot
>> Like it? Tip it!
>> http://tipit.to
>>
>
> Rémi




More information about the coin-dev mailing list