6
@FunctionalInterface
public interface GenericFunctionalInterface {
  public <T> T genericMethod();
}

I have above @FunctionalInterface and it has a generic method.

How can I use and Lambda expression to represent this Interface?

I tried below code, but it doesn't work,

GenericFunctionalInterface gfi = () -> {return "sss";};

I got compile error: Illegal lambda expression: Method genericMethod of type GenericFunctionalInterface is generic

Where can I place the type info?

3
  • See this answer and section §15.27.3 in JLS8. "A lambda expression is congruent with a function type if all of the following are true: The function type has no type parameters."
    – McDowell
    Jun 30, 2016 at 9:41
  • Do you mean “gener̲ic” method? I don’t see any connection to Genetics. Besides that, how is that supposed to work? The method <T> T geneticMethod() promises to return whatever the caller wishes, so a lambda expression return a String doesn’t fulfill that.
    – Holger
    Jul 4, 2016 at 16:32
  • Thanks Holger. it's generic. I'm wondering whether I can set the type info for the lambda expression.
    – jack yin
    Jul 6, 2016 at 3:41

1 Answer 1

10

The generic (not genetic) type parameter should be declared in the interface level, not in the method level :

public interface GenericFunctionalInterface<T> {
  public T genericMethod();
}

GenericFunctionalInterface<String> gfi = () -> {return "sss";};

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.