java use function as parameter and only care about the return value of it

Viewed 52

How to implement this function below

public T myFunction(Function<T> func)  //T is the return type
{
  //...some code
  return func();
}

And I can use the function like below, and don't need to declare parameters a, b, c in myFunction

myType result = myFunction(() -> doSomething(a, b , c))
2 Answers

The right functional interface to use then is Supplier<T>. It doesn't have an "input" type parameter:

public <T> T myFunction(Supplier<T> func) {
    // myFunction logic 
    return func.get();
}

And the invocation will be just as you have it, assuming doSomething() has myType as return type.

Unfortunately, Java is not a "Functional" language. So when you define a method like myFunction(Function<T> func) you specified, myFunction requires an Object that extends the Interface Function. Function in java declares a single method R apply(T t) in this case, Function takes a single argument. There are additional Interfaces that are part of the Java SDK such as BiFunction which has an apply method that takes two arguments. If you need a method that will take a "Function" requiring three parameters you will have to declare an Interface with those specifics. Or you could use something like. Apache Commons TriFunction

Related