函数式编程 - 一等函数
如果一个函数满足以下要求,则该函数被称为一等函数。
它可以作为参数传递给一个函数。
它可以从函数中返回。
它可以赋值给变量,然后可以在以后使用。
Java 8 使用 lambda 表达式支持函数作为一等对象。lambda 表达式是一个函数定义,可以赋值给变量、传递作为参数,并且可以返回。请参阅以下示例 -
@FunctionalInterface
interface Calculator<X, Y> {
public X compute(X a, Y b);
}
public class FunctionTester {
public static void main(String[] args) {
//Assign a function to a variable
Calculator<Integer, Integer> calculator = (a,b) -> a * b;
//call a function using function variable
System.out.println(calculator.compute(2, 3));
//Pass the function as a parameter
printResult(calculator, 2, 3);
//Get the function as a return result
Calculator<Integer, Integer> calculator1 = getCalculator();
System.out.println(calculator1.compute(2, 3));
}
//Function as a parameter
static void printResult(Calculator<Integer, Integer> calculator, Integer a, Integer b){
System.out.println(calculator.compute(a, b));
}
//Function as return value
static Calculator<Integer, Integer> getCalculator(){
Calculator<Integer, Integer> calculator = (a,b) -> a * b;
return calculator;
}
}
输出
6 6 6
广告