Question about JEP 406

Gavin Bierman gavin.bierman at oracle.com
Mon Jul 5 09:56:43 UTC 2021


Hi!

> On 21 May 2021, at 06:06, Tesla Ice Zhang <ice1000kotlin at foxmail.com> wrote:
> 
> Hi OpenJDK developers,
> 
> I'm very excited about JEP 406. Sealed classes are taken into account in switch
> expressions, which is great! However, there is one special case not mentioned in
> the JEP, about generic sealed interfaces:
> 
> 
> sealed interface Exp<T> {
>    record Add(Exp<Integer> lhs, Exp<Integer> rhs) implements Exp<Integer> {}
>    record Lit<T>(T obj) implements Exp<T> {}
> }​
> 
> In the above example, if we do a switch on an expression of type Exp<Boolean>,
> do we need to provide a case for Add?

Excellent question! Let me simplify your example:

   sealed interface I<T> permits A, B { }
   record A() implements I<Integer> {}
   record B<T>(T t) implements I<T> {}

So, if we do have a clause for A, i.e.

   I<Boolean> ib = ...;
   switch(ib) {
      case A a -> System.out.println("A");
      case B<Boolean> b -> System.out.println("B");
   }

This actually fails to typecheck, as the type pattern A a is not compatible with
the type of the selector expression, I<Boolean>:

   error: incompatible types: A cannot be converted to I<Boolean>
      case A a -> System.out.println("A");
         ^

But the real question is about exhaustiveness of the switch block. At the
moment, for a declaration like this you're going to have to provide a default
clause.  

It's a good question as to whether we can support first-class programming for
declarations of *generalized algebraic datatypes* such as the one you give.
This is still a research-level problem, but we're looking into it [1]. 

Thanks!
Gavin

[1] https://www.microsoft.com/en-us/research/publication/generalized-algebraic-data-types-and-object-oriented-programming/


More information about the amber-dev mailing list