Pattern variable and field shadowing
Zheka Kozlov
orionllmain at gmail.com
Thu Nov 28 03:55:20 UTC 2019
Hi.
I agree that the shadowing of fields is a controversial thing. Consider
these 2 examples:
First:
private String str;
...
if (obj instanceof String str) {
System.out.println(str.toLowerCase()); // refers to pattern binding
'str'
}
Second:
private String str;
...
if (obj instanceof String str || false) {
System.out.println(str.toLowerCase()); // refers to field 'str'
}
>From the user's perspective, these two pieces of code look semantically
equivalent. However, the user will be surprised when the code suddenly
starts working differently after dropping useless `|| false`.
чт, 28 нояб. 2019 г. в 10:40, Tagir Valeev <amaembo at gmail.com>:
> Hello!
>
> Consider the following code:
>
> public class A {
> private String str;
>
> public void f(Object obj) {
> if (obj instanceof String str) {
> System.out.println(str.toLowerCase()); // str refers to
> pattern binding
> } else {
> System.out.println(str.toLowerCase()); // str refers to the
> field
> }
> }
> }
>
> I thought that such a code should be rejected by the compiler, as it's
> confusing and could be a source of very subtle bugs. However, I
> haven't found any explicit statement regarding this in the latest spec
> draft [1]. Could you please clarify whether such code is acceptable
> and point me to the relevant part of the spec draft. Thank you!
>
> With best regards,
> Tagir Valeev.
>
> [1]
> http://cr.openjdk.java.net/~gbierman/jep305/jep305-20191021/specs/patterns-instanceof-jls.html
>
More information about the amber-spec-observers
mailing list