I´m currently reading through someone else´s code and he has the following two methods:
public static double fac(double d) {
return d <= 0 ? 1 : d * fac(d - 1);
}
public static DoubleUnaryOperator getfun() {
return LamdaTests::fac; // LamdaTests is the classname of this class
}
First of all, i´m currently trying to understand lambda expressions/method references.
I have 2 questions:
1) What does the getFun() method exactly do? It should call the fac(double d) method in this class LambdaTests right? But with which argument and how can the return value be a DoubleUnaryOperator, shouldn´t "LamdaTests:fac" return a double?
2) What would be the equivalent Lamda expression for Lamdatests::fac in this case?
Edit: As far as i know
return LamdaTests::fac;
should be equal to
return x -> fac(x);
But i just dont understand where it gets the argument x from.
getFun
doesn't call anything. It just returns a reference to the fac
function. You need to call the returned function still to get a result. getFac
isn't very useful here, so that may be what's confusing things. In reality, you would just use LamdaTests::fac
directly, unless that method was private.
For the latter question, think of it this way:
x -> fac(x)
is a function that takes a double and returns a double. What is fac
? It's the same thing: a function that takes a double and returns a double. The argument is just implicit here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.