2

I have a function, which takes a function and string as arguments, I want to call this function with the string argument and return the result.

Something like this:

public static String mainFunc(Callable func, String s) {
    return func.call(s); // Error
}

mainFunc(SomeObject::instanceMethod, s)

But as you can see it is not working. Please note that I don't necessarily need to use Callable, it can be any other interface.

Shota
  • 6,910
  • 9
  • 37
  • 67

1 Answers1

5

A Callable takes no parameters.

If it takes a String and returns a String, it's a Function<String, String> (or, more generally, a Function<? super String, ? extends String>).

public static String mainFunc(Function<String, String> func, String s) {
  return func.apply(s);
}

Although, there's not very much point in this method: just invoke func.apply directly.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243