Effectively final
Tim Fox
timvolpe at gmail.com
Mon Aug 15 07:41:19 PDT 2011
On 15/08/2011 15:22, Steven Simpson wrote:
> On 15/08/11 15:08, Steven Simpson wrote:
>> void foo(final Socket socket) {
>> new Object() {
>> boolean timedOut;
>> {
>> system.setTimeout(100, #{ timedOut = true; });
>> socket.onData(#{ if (!timedOut) System.out.println("Got data"); });
>> }
>> };
>> }
> I just noticed that this technique leaks 'this' before construction is
> complete. Is it generally a problem? If so, use Runnable instead:
>
> void foo(final Socket socket) {
> new Runnable() {
> boolean timedOut;
> public void run() {
> system.setTimeout(100, #{ timedOut = true; });
> socket.onData(#{ if (!timedOut) System.out.println("Got data"); });
> }
> }.run();
> }
>
> It's a little more clunky, though.
>
>
Steven, firstly thanks for putting in the effort to look at this. And
kudos for your ingenuity :)
But, let me understand this... One of the supposed advantages of Java 8
closures is to avoid having to use ugly anonymous classes in order to
implement event handlers. However, because Java 8 so-called "closures"
only allow usage with final local vars, I am forced to use anonymous
classes, as in your example (or other ugly hacks) in order to work
around that limitation? :(
I may as well just use Java <= 7.
Actually I am really disappointed by this. If these kinds (I.e.
closure/CPS style programming frameworks) of frameworks take off in the
JVM world, Java is going to be the ugly kid on the block for programming
in them. No such problem with Ruby, JavaScript, Groovy, Clojure,
Scala.... As a long time Java programmer, I think it's a real shame that
Java the language fails to modernise at the rate required to remain
relevant. Love the JVM though :)
Just my 2c of course.
More information about the lambda-dev
mailing list