crazy idea: weaken the effectively final restriction

John Rose john.r.rose at oracle.com
Wed Oct 6 17:56:43 UTC 2021


On Oct 5, 2021, at 2:55 PM, mark.yagnatinsky at barclays.com<mailto:mark.yagnatinsky at barclays.com> wrote:

Runnable f(String s) {
               s = normalize(s);
               return () -> println(s); // no can do: s is not effectively final
}

However, this seems a bit silly because although s is not final throughout the entire method, it's final where it actually matters.

As the experts have said, it is by design that the
finality can be applied to the declaration *regardless
of use*.  This yields a language that is easier to
reason about.  (Yes, we did spend a lot of complexity
budget elsewhere on lambdas as poly expressions,
which nobody understands.  To excuse that, that
bit of magic happens during overload resolution,
which nobody understood anyway.)

Namely, it is final from the point of capture to the end of the method, and that's the only condition we need to avoid those annoying questions.

I have wanted this feature from time to time, but
here’s another indication that it won’t pull its
weight (of complexity):  You can easily, even
automatically (with IDE help) work around the
limitation, simply by rebinding the variable
you intend to capture.  That’s the cost of
using the simpler (more reusable) semantics
of effectively final variables:  Sometimes
you need a second binding if the system
cannot read your mind about how you
are using the first binding.

Runnable f(String s) {
               s = normalize(s);
               var s1 = s;
               return () -> println(s1); // fixed it for you!
}

Something’s gotta give:  Either more mind-reading
rules for bindings, or more bindings.  This is arguably
the more Java-like approach.

Note also that the worst kind of mind-reading can
happen when a maintainer reads your code.  In that
case, the maintainer will surely prefer the more
transparent (though ceremonious) formulation
with s1.

Full disclosure:  As a coder I grumble every time
I have to write an “s1”.  But as a reader of code I
don’t mind them so much.

HTH




More information about the jdk-dev mailing list