Skip to content
Advertisement

When to use Functional Interface vs Function

I am using Java 11, and we have two ways of passing in functions as an argument.

  • functional interface
  • Function<T, Y>

Now I am not able to find anything on when to use which one. I can figure that we can use a generic functional interface over a Function<T,Y> when we either don’t want to pass any arguments or have more than 1 arguments. Also when we don’t want to return anything from the method.

But let’s say if we have a use case where we want to pass in 1 argument and receive 1 value back as an output. In this case, is there a recommendation on what we should pick and why? Or is it that we can pick whichever we like based on codebase uniformity.

Advertisement

Answer

Let me just cite Item 44 “Favor the use of standard functional interfaces” of Effective Java:

If one of the standard functional interfaces does the job, you should generally use it in preference to a purpose-built functional interface. This will make your API easier to learn, by reducing its conceptual surface area, and will provide significant interoperability benefits, as many of the standard functional interfaces provide useful default methods. The Predicate interface, for instance, provides methods to combine predicates.

Function<T,Y> is a @FunctionalInterface. Function<T,Y> is a built-in functional interface that has the annotation @FunctionalInterface. You have what you need with Function<T,Y> and shouldn’t create a custom @FunctionalInterface.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement