[patterns] reconsidering how the created variable name binds
John Rose
john.r.rose at oracle.com
Sat Dec 28 20:47:12 UTC 2019
> 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 is also a prototype for a future syntax, a statement which binds one or more pattern variables and has an implicit exception path (if the pattern isn’t total). Still on the drawing board I think.
static String v = "field";
public void test(CharSequence obj) {
__LetPattern String v __Match obj
System.out.println(v);
}
This looks more like a declaration but it piggybacks on the same innovation, that a pattern can export bindings to its control flow successors.
If you repair the (indefinite) rule you propose to allow this case, and keep going, eventually your rule becomes moot, since it will (surprise) allow all the cases that the current proposal does. I’m pretty sure the core designers have anticipated all the relevant examples already.
(Just in case someone was starting to object “but coders should never code in that style anyway”: No. That is not how Java is designed, also. Whether you consent to eat some particular form of syntactic broccoli is up to you.)
HTH
– John
More information about the amber-dev
mailing list