There is such code:

interface SomeFunc<T> { T func(T t); } public class LambdaDemo { public static void main(String[] args) { SomeFunc<String> reverse = (str) -> { String result = ""; for (int i = str.length()-1; i >= 0; i--) { result += str.charAt(i); } return result; }; Rever foo = new Rever(); foo.doSmth(reverse, "reverse"); } } class Rever { public void doSmth(SomeFunc<?> func, String n) { System.out.println(func.func(n)); } } 

But the compiler produces the following error:

[Java] The method of func(capture#1-of ?) In the type SomeFunc<capture#1-of ?>

What is my mistake and how to fix it?

  • The problem is this line: (SomeFunc <?> Func, String n) You say: Take any function (SomeFunc <Integer> for example) and pass the String into it. Do it instead (SomeFunc <String> func, String n) - aleshka-batman
  • one
    Or use this option: public <T> void doSmth (SomeFunc <T> function, T n) - aleshka-batman
  • @ aleshka-batman, I think this can be duplicated as an answer. I will add that the declaration of the SomeFunc interface is superfluous, since for this purpose the standard library has UnaryOperator<T> , which is the successor of Function<T, T> - iksuy
  • one
    @ aleshka-batman, post your comment as an answer. public <T> void doSmth (SomeFunc <T> function, T n) is what you need. Thank. - WenSiL

0