? extend T[] is not considered an array
Attila Kelemen
attila.kelemen85 at gmail.com
Sat Feb 24 23:02:35 UTC 2024
Thanks, I have reread the spec more carefully, and you are right: A strict
interpretation of the spec does require this behavior (and who could fault
the compiler to strictly follow the spec). Though I'm guessing this
behavior was not the intent of the JLS just happened to be so due to this
not being a possibility before Java 5 (since Java - as far as I know -
nowhere requires upcasting besides disambiguating method overloads, and I
can see no benefit to mandate it here as well).
Also, thanks for the link to the bug report, at least I know that this is
not an unknown issue. Though since the first issue on this was opened in
2007 (JDK-6557960) I won't hold my breath for this to be fixed :)
Attila
Maurizio Cimadamore <maurizio.cimadamore at oracle.com> ezt írta (időpont:
2024. febr. 23., P, 15:25):
> Hi,
> as currently specified, the type of the expression used in array access
> must be an array type - see JLS 15.10.3
>
> The type of the array reference expression must be an array type (call it
> T[], an array whose components are of type T), or a compile-time error
> occurs.
>
> There is nothing in the JLS to suggest that an array type is anything
> other than some type T followed by array brackets. E.g. in JLS 10.1:
>
> An array type is written as the name of an element type followed by some
> number of empty pairs of square brackets []. The number of bracket pairs
> indicates the depth of array nesting.
>
> So, javac is behaving as specified in the JLS. Note that wildcards are a
> distraction here. The wildcard generates a captured type - that is a type
> variable whose upper bound is an array type.
>
> The following program:
>
> ```
> class Foo<X extends Object[]> {
> void test(X x) { Object o = x[0]; }
> }
> ```
>
> Exhibits the same behavior - e.g. it fails to compile, because "x" is not
> an array.
>
> So, the question you are asking is: why can't we assume that a
> type-variable whose upper bound is an array type is also an array type?
>
> This is discussed here:
>
> https://bugs.openjdk.org/browse/JDK-8013843
>
> My reading is that it's doable, but it's work to make sure that nothing
> else gets affected. E.g. if we treat as array anything that has an array
> supertype, then the "null type" might get tangled in the mix (e.g.
> null[0]). Of course this is not a reason for not doing it - but some care
> is required. For-each loops might be affected as well.
>
> Cheers
> Maurizio
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20240225/a81a2cff/attachment-0001.htm>
More information about the compiler-dev
mailing list