Unexpected compilation error with generic sealed interface

Remi Forax forax at univ-mlv.fr
Sun Dec 27 22:40:50 UTC 2020


----- Mail original -----
> De: "mark" <mark at io7m.com>
> À: "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Envoyé: Dimanche 27 Décembre 2020 22:04:43
> Objet: Unexpected compilation error with generic sealed interface

> Hello!
> 
> A friend of mine handed me this example that fails to compile using
> JDK 17 EA 3:
> 
> ~~
> final class SealedExample
> {
>  private SealedExample()
>  {
> 
>  }
> 
>  // Compiles if you remove `sealed` or if `I` is not generic.
>  sealed interface I<T> {
>    final class C implements I<Object> { }
>  }
> 
>  static void f(final I<Object> x) {
>    if (x instanceof I.C) {
> 
>    }
>  }
> }
> ~~
> 
> The error is:
> 
> ~~
> src/main/java/SealedRecord.java:14: error: incompatible types:
> I<Object> cannot be converted to C if (x instanceof I.C) {
>        ^
> 1 error
> ~~
> 
> The error goes away if you remove the word "sealed" from the
> interface. In her words: "It breaks simple things like Option.".
> 
> I can see the reasoning required on behalf of the compiler: You've
> handed me an I<Object>, and by the definition of I, there's exactly one
> class that could yield an I<Object>: C.
> 
> I'm unsure of whether the compiler should be rejecting these
> definitions or not.

Hi Mark,
this is an interesting snippet, while i struggle to understand why someone want to write a code like that, I is parametrized by T but the only possible subclass implements I<Object> so T is useless here,
anyway, the compiler should not reject that code so it's a bug.

I've also tested with latest Eclipse and IntelliJ and in both cases it compiles fine.

> 
> --
> Mark Raynsford | https://www.io7m.com

Rémi


More information about the amber-spec-experts mailing list