我的理解前向引用錯誤,但爲什麼我必須通過以下內容去 define n! ? 我已經註釋掉了錯誤,並添加了我看到的編譯器錯誤。Java 1.8遞歸lambdas
import java.util.function.Function;
class Recursion {
Function<Integer, Integer> factorial_lambda = null;
int factorial_imp(int i) {
if (i == 1)
return 1;
else
return i * factorial_imp(i - 1);
}
/*
Function<Integer, Integer> factorial_lambda = (i) -> {
if (i == 1)
return 1;
else
return i * (factorial_lambda.apply(i - 1));
// error: self-reference in initializer
};
*/
public static void main(String[] args) { new Recursion(); }
public Recursion() {
/*
Function<Integer, Integer> factorial_lambda = (i) -> { return 1; };
// variable used in lambda expression should be final
// or effectively final;
// Function factorial_lambda = (i) -> { ...
//error: imcomparable types: Object and int if (i == 1)
//error: bad operand types for binary operator '-' apply(i - 1)
*/
factorial_lambda = (i) -> {
if (i == 1)
return 1;
else
return i * (factorial_lambda.apply(i - 1));
};
System.out.println(factorial_imp(5));
System.out.println(factorial_lambda.apply(5));
}
}
它爲我編譯和正常工作。你使用什麼編譯器? – kraskevich 2014-11-08 18:34:31
對不起。問題是爲什麼各種評論代碼片段不起作用。例如,我無法在遞歸()中本地定義lambda factorial_lambda。 – Jerrolds 2014-11-08 19:47:02