Search code examples
javajava-8functional-programmingfunctional-interface

Functional Interface Implementations and use cases


I was just trying to write a functional interface to understand the different use cases.

Looking at the below code which I have written, I understand that I can have different implementations using lambda expressions. Apart from this can anyone show the complex implementations?

Is it possible to use other default method i.e. addLikeOtherWay in lambda expression? if yes how in my example?

Why would I have interface with only one abstract method? What would be the use case of having only single abstract method in my interface?

public class Calculator {

    public static void main(String[] args) {
        ICalculator i = (int a, int b) -> a + b;
        System.out.println(i.add(5, 2));
        i = (int a, int b) -> a + b + a;
        System.out.println(i.add(5, 2));
    }
}

@FunctionalInterface
interface ICalculator {

    public int add(int a, int b);

    default int addLikeThis(int a, int b) {
        return a + b;
    }

    default int addLikeOtherWay(int a, int b) {
        return a + b + a + b;
    }

}

Solution

  • Why would I have interface with only one abstract method? What would be the use case of having only single abstract method in my interface?

    To facilitate the use of lambda expressions , which are nameless functions. Lambda expressions make code expressive and reduce clutter. It also makes code more readable. This is based my experience working with lambda expressions.