Functional Programming - First Class Function
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 from version 8 onwards 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.
Example - Calling a Function as Function Variable
FunctionTester.java
package com.tutorialspoint;
@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));
}
}
Output
Run the FunctionTester and verify the output.
6
Example - Passing a Function as a parameter
FunctionTester.java
package com.tutorialspoint;
@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;
//Pass the function as a parameter
printResult(calculator, 2, 3);
}
//Function as a parameter
static void printResult(Calculator<Integer, Integer> calculator, Integer a, Integer b){
System.out.println(calculator.compute(a, b));
}
}
Output
Run the FunctionTester and verify the output.
6
Example - Getting a function as a return
FunctionTester.java
package com.tutorialspoint;
@FunctionalInterface
interface Calculator<X, Y> {
public X compute(X a, Y b);
}
public class FunctionTester {
public static void main(String[] args) {
//Get the function as a return result
Calculator<Integer, Integer> calculator1 = getCalculator();
System.out.println(calculator1.compute(2, 3));
}
//Function as return value
static Calculator<Integer, Integer> getCalculator(){
Calculator<Integer, Integer> calculator = (a,b) -> a * b;
return calculator;
}
}
Output
Run the FunctionTester and verify the output.
6
Advertisements