<div dir="ltr"><div><div><div><div>Hello amber-dev folks!<br><br></div><div>While using pattern matching for instanceof I noticed a small incoherent oddity.<br></div><div><br></div><div>Take this code:</div><div>```<br>static void ensureCapacity(List l) {<br> if (l instanceof LinkedList) {<br> throw new IllegalArgumentException("Use an efficient list implementation");<br> } else if (!(l instanceof ArrayList al)) {<br> return;<br> }<br> al.ensureCapacity(10);<br> System.out.println("done");<br>}<br><br>ensureCapacity(new ArrayList());</div>```<br><br>The compiler rejects this code with: `Cannot resolve symbol 'al'`.<br>(I have tested that code with JDK 24 in the playground (<a href="https://dev.java/playground">https://dev.java/playground</a>) but also in my IDE with JDK 21)<br><br></div>However #1, removing the `else` keyword makes the code successfully compile:<br>```<br> }</div><div> if (!(l instanceof ArrayList al)) {<br> return;<br> }</div><div>```<br><br>However #2, adding an additional `else` keyword makes the code successfully compile:<br>```<br> } else if (!(l instanceof ArrayList al)) {<br> return;<br> } else {<br> al.ensureCapacity(10);<br> System.out.println("done");<br> }</div><div>```<br></div><div><br></div><div>While option #1 and #2 are acceptable workarounds, it looks to me like there could be a bug in javac? Therefore I am bringing this to your attention so you can decide if it is a bug or not.</div><div><br></div>I searched the JDK's bug tracker for this specific case, but could not find anything related.<br><br></div><div>Thanks!</div><div>Jean-Noël</div></div>
<br>
<i style="margin:0px;padding:0px;border:0px;outline:0px;vertical-align:baseline;background:rgb(255,255,255);font-family:proxima-nova-zendesk,system-ui,-apple-system,system-ui,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",Arial,sans-serif;color:rgb(85,85,85)"><span style="margin:0px;padding:0px;border:0px;outline:0px;vertical-align:baseline;background:transparent;font-family:proxima-nova-zendesk,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",Arial,sans-serif;font-weight:600"><font size="2">CONFIDENTIALITY NOTICE: This email may contain confidential and privileged material for the sole use of the intended recipient(s). Any review, use, distribution or disclosure by others is strictly prohibited. If you have received this communication in error, please notify the sender immediately by e-mail and delete the message and any file attachments from your computer. Thank you.</font></span></i>