? extend T[] is not considered an array
Attila Kelemen
attila.kelemen85 at gmail.com
Sat Jan 13 12:38:06 UTC 2024
Hi,
I have not found anything in JLS specifically mentioning this. So, I'm not
sure if it is intentional, but the following code does not compile (in any
versions of Java I have tried):
```
interface ForEachable<T> {
void forEach(Consumer<? super T> consumer);
}
List<String> wrongMethod(ForEachable<? extends String[]> arrays) {
var result = new ArrayList<String>();
arrays.forEach(array -> result.add(array[0]));
return result;
}
```
or in an even simpler example:
```
String first(Supplier<? extends String[]> supplier) {
return supplier.get()[0];
}
```
The compiler complains about `array[0]` that `array` is not an array. While
I get that the compiler cannot assume that there is no subtype of
`String[]`, but even if there was one, I would expect it to be an
array, and be indexable.
An obvious workaround is to assign `array` to a new local variable, but it
is awkward to do.
Is this behavior a bug, or something required by the JLS?
Thanks,
Attila
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20240113/dfcf267f/attachment.htm>
More information about the compiler-dev
mailing list