Resolving methods for all in a sealed hierarchy

Vikram Bakshi vab2048 at gmail.com
Fri Jul 29 21:41:05 UTC 2022


Hello all,

Suppose we have the following sealed hierarchy (I've removed the fields
from the records for brevity):

```java
    sealed interface Command permits A, B, C {}
    public record A() implements Command {}
    public record B() implements Command {}
    public record C() implements Command {}
```

And the following class:

```java
    public class CommandHandler {

        public void handle(A a) { System.out.println("Handling A"); }
        public void handle(B a) { System.out.println("Handling B); }
        public void handle(C a) { System.out.println("Handling C"); }
    }
```

If we then try to pass a `Command` to an instance of `CommandHandler` we
get an error:

```java
        var commandHandler = new CommandHandler();
        Command command = new A();
        commandHandler.handle(command); // ERROR: cannot resolve method
```

Obviously casting it works:

```java
        switch(command) {
            case A cmd-> commandHandler.handle(cmd);
            case B cmd-> commandHandler.handle(cmd);
            case C cmd-> commandHandler.handle(cmd);
        }
```

My question is will the Java compiler ever be able to resolve the method
automatically given that the sealed hierarchy has a corresponding method.

I realise this would be a low priority on your delivery path but was
interested in understanding if there is something that would stop it from
being delivered in the future.

Cheers,
Vikram
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220729/c363cd8c/attachment.htm>


More information about the amber-dev mailing list