Generic Functional Interfaces

Java-Generic Functional Interfaces

Generic Functional Interfaces

It is possible to declare generic functional interfaces. To understand the value of generic functional interfaces, consider the two different functional interfaces, one called StringYear and the other called IntYear :

Generic Functional Interfaces
Both interface defined a method called getYear( ) that returned a result. In the first case, the return type was String. In the second case, the return type was int. Thus, the only difference between the two methods was the type of data they returned. Instead of having two functional interfaces whose methods differ only in their return types, it is possible to declare one generic interface that can be used to handle both circumstances.

Generic Functional Interfaces
The following program shows this approach. In the program, the generic functional interface Year is declared. T specifies the return type of getYear( ). This means that it is compatible with any lambda expression that returns one value. The Year interface is used to provide a reference to two different types of lambdas. The first returns type Integer. The second returns type String. Thus, the same functional interface can be used to refer to the intYear lambda and the stringYear lambda.

A lambda expression, itself, cannot specify type parameters. Thus, a lambda expression cannot be generic. However, the functional interface associated with a lambda expression can be generic. In this case, the target type of the lambda expression is determined, in part, by the type argument or arguments specified when a functional interface reference is declared.


Generic Functional Interfaces Private Interface Methodss

Program Source

interface Year<T> {
    T getYear();
class Javaapp {
    public static void main(String[] args) {
        Year<Integer> intYear = ()-> 2018 ;
        int yearInt = intYear.getYear();
        Year<String> stringYear = ()-> "2018" ;
        String yearString = stringYear.getYear();
        System.out.println("yearInt    : "+yearInt);
        System.out.println("yearString : "+yearString);

Leave a Comment