English 中文(简体)
First Class Functions
  • 时间:2024-12-22

Functional Programming - First Class Function


Previous Page Next Page  

A function is called a first class function if it fulfills the following requirements.

    It can be passed as a parameter to a function.

    It can be returned from a function.

    It can be assigned to a variable and then can be used later.

Java 8 supports functions as first class object using lambda expressions. A lambda expression is a function definition and can be assigned to a variable, can be passed as an argument and can be returned. See the example below −

@FunctionalInterface
interface Calculator<X, Y> {    
   pubpc X compute(X a, Y b);
}

pubpc class FunctionTester {    
   pubpc 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;
   }
}

Output

6
6
6
Advertisements