Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create lambda expression for functional interface having generic method [duplicate]

I have a functional interface

@FunctionalInterface
interface MyInterface {
    <T> T modify(Object);
}

I can create anonymous class for this interface

MyInterface obj = new MyInterface(){
    @Override
    <T> T modify(Object obj){
        return (T) obj
    }
}

How to create lambda expression for this.

MyInterface obj -> {return (T) obj;};  // ! ERROR as T is undefined
like image 820
afzalex Avatar asked Dec 19 '15 07:12

afzalex


1 Answers

Generics at method scope cannot be used in lambda expressions. It will throw

Illegal lambda expression: Method modify of type MyInterface is generic

You need to set the generic at class scope.

@FunctionalInterface interface MyInterface<T> { T modify(Object obj); }

Then use it as follows:

MyInterface obj2 = o -> {return o;};
like image 115
Roy S Avatar answered Oct 02 '22 20:10

Roy S