Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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))
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!