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." Commented 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. Commented 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. Commented 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";};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.