Resolving methods for all in a sealed hierarchy
Brian Goetz
brian.goetz at oracle.com
Fri Jul 29 21:45:08 UTC 2022
The three methods in your CommandHandler are overloads. Method overload
selection in Java is always done on the _static_ types of the
arguments. If you want dispatch on the _dynamic_ type of the argument,
you have three choices:
- virtual method dispatch (declaration-site polymorphism)
- Visitor pattern (make Command know about CommandHandler, and put a
handle(handler) method in Command)
- Pattern matching (use-site polymorphism)
Short answer: for your case, use pattern matching.
On 7/29/2022 5:41 PM, Vikram Bakshi wrote:
> 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/7f4b6ca7/attachment-0001.htm>
More information about the amber-dev
mailing list