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?

Holger
  • 285,553
  • 42
  • 434
  • 765
jack yin
  • 61
  • 1
  • 2
  • See [this answer](http://stackoverflow.com/a/22588738/304) and section [§15.27.3](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-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 '16 at 09: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 geneticMethod()` promises to return whatever the caller wishes, so a lambda expression return a `String` doesn’t fulfill that. – Holger Jul 04 '16 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 06 '16 at 03:41

1 Answers1

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";};
Eran
  • 387,369
  • 54
  • 702
  • 768