Pattern variable and field shadowing

Gavin Bierman gavin.bierman at
Tue Dec 3 10:33:00 UTC 2019

> On 2 Dec 2019, at 22:59, Remi Forax <forax at> wrote:
> ----- Mail original -----
>> De: "Gavin Bierman" <gavin.bierman at>
>> À: "Tagir Valeev" <amaembo at>
>> Cc: "amber-spec-experts" <amber-spec-experts at>
>> Envoyé: Lundi 2 Décembre 2019 13:18:43
>> Objet: Re: Pattern variable and field shadowing
>> Hi Tagir,
>> No, that’s very much the expected behaviour. The idea of flow scoping is that a
>> pattern variable is only *in scope* where it has definitely matched. Thus, in
>> places where it is definitely not matched - like your else block - it is not in
>> scope. Thus it doesn’t exist. Thus if there is field with that name, then that
>> is the meaning of the name.
>> We looked long and hard at exactly this example; as Brian mentioned, it is
>> called the “Swiss cheese” problem in the team! The problem is that not doing
>> this also comes at a heavy cost. For example, we could say that the variable
>> str in your example is in scope but not DA, for example. But that means that
>> using a pattern variable poisons it forever more in the statement/block. This
>> forbids very, very common code like:
>> if (a instanceof Point p) {
>>>> } else {
>>   if (b instanceof Point p) { // Can’t use p even though it won’t be bound
>>>>   }
>> }
>> In other words, you’ll have to find a new pattern variable everytime. [And this
>> gets even worse in switch.] That’s a real pain, and I think most people will
>> say “why do I have to find a new name, can’t you figure it out?”. Yes, we
>> could, but then we’d have to do something even more special case, like allowing
>> shadowing of pattern variables with pattern variables. But we’re now
>> unravelling all sorts of aspects of the way Java deals with naming, and that
>> feels like something that most users will never have in their heads. We’re
>> hoping the “only in scope where it is matched” is a simpler rule that is easier
>> to internalize.
>> That’s not to say that there couldn’t be tooling to provide warnings in the case
>> where pattern variables shadow fields (as it inevitably means that there will
>> be some holes in the cheese), hint hint :-)
> why not javac being "the tooling" ?
> I think it will be useful for our users if javac emit such warning (if the linter is activated).

Noted :-)


More information about the amber-spec-experts mailing list