函數語言程式設計 - 一等函式



如果一個函式滿足以下要求,則該函式被稱為一等函式。

  • 它可以作為引數傳遞給一個函式。

  • 它可以從函式中返回。

  • 它可以賦值給變數,然後可以在以後使用。

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
廣告
© . All rights reserved.