Unexpected compilation error with generic sealed interface

Mark Raynsford mark at io7m.com
Sun Dec 27 21:04:43 UTC 2020


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.

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



More information about the amber-spec-experts mailing list