[patterns] reconsidering how the created variable name binds
Remi Forax
forax at univ-mlv.fr
Sat Dec 28 23:20:30 UTC 2019
----- Mail original -----
> De: "John Rose" <john.r.rose at oracle.com>
> À: "Reinier Zwitserloot" <reinier at zwitserloot.com>
> Cc: "amber-dev" <amber-dev at openjdk.java.net>
> Envoyé: Samedi 28 Décembre 2019 21:47:12
> Objet: Re: [patterns] reconsidering how the created variable name binds
>> On Dec 28, 2019, at 9:52 AM, Reinier Zwitserloot <reinier at zwitserloot.com>
>> wrote:
>>
>> static /*?final?*/ boolean FLAG = true;
>> static String v = "field";
>> public void test() {
>> String obj = "Pattern match";
>> if (!(obj instanceof String v)) {
>> // This branch is never taken.
>> while (FLAG) ; // endless
>> }
>>
>> System.out.println(v);
>
> Yes, DU and static final are both examples of action at a distance and they can
> be combined. Add inheritance of the final for an extra-good time. Such puzzlers
> do not usually drive the design of the language, as you surmise later on; at
> some point (including here IMO) we can agree to say, “yeah, but that’s an
> academic point”.
>
> IIUC your proposal (which isn’t complete since it fails to define the [B]
> condition; it only suggests it AFAICS) makes pattern matching work less well
> with fall-through. Would the following example fail under your proposal? I
> think that would be a much larger downside than the academic one you cite.
>
> static String v = "field";
> public void test(CharSequence obj) {
> if (!(obj instanceof String v)) {
> // Report error. Rarely taken.
> throw stuff();
> }
>
> System.out.println(v);
> }
>
> Here the if statement has no else clause. The fall-through path is where you go
> when the pattern doesn’t match. I changed String obj to be CharSequence to make
> it more realistic. (Does that lose the point of your example?)
This use case is important, there is a lot code where equals() is written like this:
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point p = (Point) obj;
return x == p.x && y == p.y;
}
and obviously you want to transform it to:
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Point p)) {
return false;
}
return x == p.x && y == p.y;
}
[...]
>
> – John
Rémi
More information about the amber-dev
mailing list