java - 在 Java 中实现递归 lambda 函数

标签 java recursion lambda

我不知道下面的事情是否可行。我想要一个 Runnablerun() 方法来包含 Runnable 本身,即

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();
        //...
    }
};

这样的事情有可能吗?如果是这样,如何? (CmdRun 的构造函数是 CmdRun(String command, Runnable executeAfter))

最佳答案

这里必须使用 lambda 吗?如果不是,切换到旧的等效语法应该很简单:

一个例子:

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();
    }
}

关于java - 在 Java 中实现递归 lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40624587/

相关文章:

java - 将图像放在 JButton 上方(而不是内部)并使 JButton 仍然工作

c++使用指针和状态机构建递归树

python - 在递归函数中定义内部函数是个坏主意吗?

c++ - 查找背包中带了哪些元素

asp.net - 如果结果集为空,Linq lambda 表达式抛出错误

javascript - 通过 Google App Script 调用 AWS Lambda 函数

java - 编写最新的或兼容的代码是更好的做法吗?

java - 如何将复选框放在 Swing 中的文本字段下方?

java - 使用 Java 在 MongoDB 中插入字符串数组

Java 8 流 : Map the same object multiple times based on different properties