<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<font size="4"><font face="monospace">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:<br>
<br>
- virtual method dispatch (declaration-site polymorphism)<br>
- Visitor pattern (make Command know about CommandHandler, and
put a handle(handler) method in Command)<br>
- Pattern matching (use-site polymorphism)<br>
<br>
Short answer: for your case, use pattern matching. <br>
<br>
</font></font><br>
<div class="moz-cite-prefix">On 7/29/2022 5:41 PM, Vikram Bakshi
wrote:<br>
</div>
<blockquote type="cite" cite="mid:CANExk-6oeEpa6U6Ui7ap-JmrDiAx_Xyx_Ds=MacYoWb2BR=0iQ@mail.gmail.com">
<div dir="ltr">Hello all,
<div><br>
</div>
<div>Suppose we have the following sealed hierarchy (I've
removed the fields from the records for brevity):</div>
<div><br>
</div>
<div>```java</div>
<div> sealed interface Command permits A, B, C {}<br>
public record A() implements Command {}<br>
public record B() implements Command {}<br>
public record C() implements Command {}<br>
</div>
<div>```<br>
</div>
<div><br>
</div>
<div>And the following class:</div>
<div><br>
</div>
<div>```java</div>
<div> public class CommandHandler {<br>
<br>
public void handle(A a) { System.out.println("Handling
A"); }<br>
public void handle(B a) { System.out.println("Handling
B); }<br>
public void handle(C a) { System.out.println("Handling
C"); }<br>
}</div>
<div>```</div>
<div><br>
</div>
<div>If we then try to pass a `Command` to an instance of
`CommandHandler` we get an error:</div>
<div><br>
</div>
<div>```java</div>
<div> var commandHandler = new CommandHandler();<br>
Command command = new A();<br>
commandHandler.handle(command); // ERROR: cannot
resolve method</div>
<div>```</div>
<div><br>
</div>
<div>Obviously casting it works:</div>
<div><br>
</div>
<div>```java</div>
<div> switch(command) {<br>
case A cmd-> commandHandler.handle(cmd);<br>
case B cmd-> commandHandler.handle(cmd);<br>
case C cmd-> commandHandler.handle(cmd);<br>
}</div>
<div>```</div>
<div><br>
</div>
<div>My question is will the Java compiler ever be able to
resolve the method automatically given that the sealed
hierarchy has a corresponding method.</div>
<div><br>
</div>
<div>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.</div>
<div><br>
</div>
<div>Cheers, </div>
<div>Vikram</div>
<div><br>
</div>
</div>
</blockquote>
<br>
</body>
</html>