dotwin dotwin - 17 days ago 5
Java Question

Implementing a recursive lambda function in Java

I don't know if the following thing is possible. I would like a

Runnable
's
run()
method to contain the
Runnable
itself, i.e.

reconnects = 3;
Runnable executeAfter = () -> {
if ( --reconnects < 0 ) {
println("%nStop using port %d.", this.port);
//...
} else { // try to reconnect
println("%nReconnecting...");
cmdRun = new CmdRun(command, executeAfter);
(new Thread(cmdRun)).start();
//...
}
};


Is something like this even possible? If so, how? (
CmdRun
's constructor is
CmdRun(String command, Runnable executeAfter)
)

Answer

Is lambda a must here? If not, switching to older equivalent syntax should be simple:

An example:

public class TestLambda {
    static int count = 0;
    public static void main(String[] args) {
        // lambda not going to work
        //Runnable foo = () -> { if (count < 5) { call(foo); } };
        // nor
        //Runnable foo = () -> { if (count < 5) { call(this); } };

        // using old way of anonymous inner class will work
        Runnable foo = new Runnable() {
            @Override public void run() {
                if (count < 5) {
                    call(this);
                }
            }
        };

        foo.run();
    }

    public static void call(Runnable action) {
        count++;
        System.out.println("in call " + count);
        action.run();
    }
}
Comments