"Cannot resolve symbol al" after `else if (! (l instanceof ArrayList al))`

Jean-Noël Rouvignac jean-noel.rouvignac at pingidentity.com
Wed Apr 16 09:37:32 UTC 2025


Hello amber-dev folks!

While using pattern matching for instanceof I noticed a small incoherent
oddity.

Take this code:
```
static void ensureCapacity(List l) {
  if (l instanceof LinkedList) {
    throw new IllegalArgumentException("Use an efficient list
implementation");
  } else if (!(l instanceof ArrayList al)) {
    return;
  }
  al.ensureCapacity(10);
  System.out.println("done");
}

ensureCapacity(new ArrayList());
```

The compiler rejects this code with: `Cannot resolve symbol 'al'`.
(I have tested that code with JDK 24 in the playground (
https://dev.java/playground) but also in my IDE with JDK 21)

However #1, removing the `else` keyword makes the code successfully compile:
```
  }
  if (!(l instanceof ArrayList al)) {
    return;
  }
```

However #2, adding an additional `else` keyword makes the code successfully
compile:
```
        } else if (!(l instanceof ArrayList al)) {
            return;
        } else {
            al.ensureCapacity(10);
            System.out.println("done");
        }
```

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.

I searched the JDK's bug tracker for this specific case, but could not find
anything related.

Thanks!
Jean-Noël

-- 
_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._
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20250416/0ebda756/attachment-0001.htm>


More information about the amber-dev mailing list