7

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
afzalex
  • 8,598
  • 2
  • 34
  • 61

1 Answers1

5

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;};
Roy S
  • 159
  • 7