Incompilable instanceof with super-bound

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Thu Mar 16 10:21:37 UTC 2023


It seems an issue with cast conversion? E.g. the following:

|Sub<?> ss = (Sub<?>)next; |

Also fails (with same error). Now, there are two questions here:

 1. should the cast be statically rejected - this means asking whether
    |Sub<?>| and |Super<? super Box<?>>| are provably distinct
    parameterized types;
 2. should the cast be allowed without warnings - this means proving
    that there is only one possible way to go from a |Super<? super
    Box<?>>| down to a |Sub<?>|;

But, before I try to reply any of this questions - can you please 
confirm me that there is another error in this program - namely with 
|isSub(new Sub<>())| (I seem to get an inference failure here for the 
diamond expression).

Maurizio

On 16/03/2023 10:01, Tagir Valeev wrote:

> Hello!
>
> We've stumbled with the following code sample:
>
> class Test {
>     public static boolean isSub(Super<? super Box<?>> next) {
>         return next instanceof Sub<?>;
>     }
>
>     static class Super<T> {}
>
>     static class Sub<T> extends Super<Box<T>> { }
>
>     static class Box<T> {}
>
>     public static void main(String[] args) {
> System.out.println(isSub(new Sub<>()));
> }
> }
>
> javac 21-ea+12-971 reports an error here:
>
> Test.java:3: error: incompatible types: Super<CAP#1> cannot be 
> converted to Sub<?>
>         return next instanceof Sub<?>;
>                ^
>   where CAP#1 is a fresh type-variable:
>     CAP#1 extends Object super: Box<?> from capture of ? super Box<?>
> 1 error
>
> On the other hand, Eclipse compiler compiles this correctly. From my 
> understanding of the specification, this code should be accepted. 
> Could you please take a look?
>
> Thank you in advance,
> Tagir Valeev.

​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20230316/e683d1d0/attachment-0001.htm>


More information about the compiler-dev mailing list