使用Java 8实现递归lambda函数 [英] Implement recursive lambda function using Java 8

查看:2193
本文介绍了使用Java 8实现递归lambda函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 8引入了lambda函数,我想实现像factorial这样的东西:

Java 8 introduced lambda functions and I want to implement something like factorial:

 IntToDoubleFunction fact = x -> x == 0 ? 1 : x * fact.applyAsDouble(x-1);

编译返回

  error: variable fact might not have been initialized

如何引用函数本身。类是匿名的但实例存在:它被称为 fact

How can I reference function itself. Class is anonymous but instance exists: It is called fact.

推荐答案

我通常使用(一次为所有功能接口定义)通用助手类,它包装了功能接口类型的变量。
这种方法解决了局部变量初始化的问题,并允许代码看起来更清晰。

I usually use (once-for-all-functional-interfaces defined) generic helper class which wraps the variable of the functional interface type. This approach solves the problem with the local variable initialization and allows the code to look more clearly.

如果出现此问题,代码将如下所示:

In case of this question the code will look as follows:

// Recursive.java
// @param <I> - Functional Interface Type
public class Recursive<I> {
    public I func;
}

// Test.java
public double factorial(int n) {

    Recursive<IntToDoubleFunction> recursive = new Recursive<>();
    recursive.func = x -> (x == 0) ? 1 : x * recursive.func.applyAsDouble(x - 1);

    return recursive.func.applyAsDouble(n);
}

这篇关于使用Java 8实现递归lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆