In: Computer Science
Using Java, Explain how to implement a functional interface using a lambda expression. You may include small sections of code to illustrate your explanation.
Functional interface is an interface that has only one abstract method.
Lamda expression is used to represent the instance of functional interface.
Means using lamda expression we can write definition of an abstract method.
Suppose if we have a functional interface square,
@FunctionalInterface
interface Square
{
int calculateSquare(int x);
}
We can use @FunctionalInterface annotaton to functional interface but it is optional. Above functional interface has one abstract method calculateSquare.
To define the implementation of that method, we can write lamda expression as below :
Square s = (int x) -> x*x;
Means it accepts one parameter and performs square of it.
//functional interface that has only one abstract method
@FunctionalInterface
interface Square
{
int calculateSquare(int x);
}
public class Main
{
public static void main(String[] args) {
//lambda expression to define the calculateSquare method
//means implementation of calculateSquare method.
Square s = (int x) -> x*x;
// parameter passed and return type must be
// same as defined in the prototype
int ans = s.calculateSquare(5);
System.out.println(ans);
}
}
Please refer below screenshot of code for indentation and output.