Functional Interface using generics

Sharing is caring

In the previous examples on the basics of functional programming, we had created 2 types of functional interfaces. First one was neither accepting nor returning any parameter. The second one was accepting two integers, and returning an integer. Using lambda expression, we made the second one return sum or product based on our requirement. BUT, now our requirement is to concatenate two strings. Can I use the same interface or have to create a new one.

As our current functional interface, NumberCalculator is accepting two integers (as below) and in the new requirement, we have two strings to concatenate, we cannot reuse the same.

@FunctionalInterface

public interface NumberCalculator {

       public int compute(int a, int b);

}

To solve this issue, we can use the concept of Generics.

What is generics?

Generics is an extension of Java programming language introduced with JDK 5.0. Generics allows us to abstract over types.

In the above scenario, instead of specifying the datatype as int, we can assign a dynamic value which can be replaced by actual datatypes based on requirement.

Let’s look at the following example.

@FunctionalInterface

public interface GenericFunction<R,A,B> {

       public R process(A a,B b);

}

Here A, B will be replaced by the datatype of input and R is the datatype of the value being returned. Let’s look at the following code.

GenericFunction<Integer,Integer,Integer> numberFunction = (a,b) -> a + b;

GenericFunction<String, String, String> textFunction = (a,b) -> a + b;

System.out.println(numberFunction.process(4,8));

System.out.println(textFunction.process(“This is “, “the magic of functional programming”));

Here the values <Integer, Integer, Integer> corresponds to <R, A, B> in the same sequence.

The final code looks like

GenericFPClient.java

public class GenericFPClient {

       public static void main(String[] args) {

             GenericFunction<Integer,Integer,Integer> numberFunction = (a,b) -> a + b;

             GenericFunction<String, String, String> textFunction = (a,b) -> a + b;

             System.out.println(numberFunction.process(4,8));

             System.out.println(textFunction.process(“This is “, “the magic of functional programming”));

       }

}

GenericFunction.java

@FunctionalInterface

public interface GenericFunction<R,A,B> {

       public R process(A a,B b);

}

On running the above code, the output will be as below

Even though we have used generics to reuse the functional interfaces for various scenarios and reduce lines of codes, still we need to create new functional interfaces for many scenarios. Java came up with built in functional interfaces which covers most of the common scenarios. We will look into it in our next article.


Sharing is caring

Leave a Reply

Your email address will not be published. Required fields are marked *