What's the nearest substitute for a function pointer in Java?
Java, not having function pointers, embraces functional interfaces you can implement using lambdas or method references. The java.util.function
has ready-to-use interfaces like Function<T,R>
for functions that receive type T and return R. Here's an illustrative example of lambda expression:
This transforms the length()
method into a lambda that behaves as a function pointer.
Functional Interfaces and Lambdas: Let's get functional
Before Java 8, anonymous inner classes were used to encapsulate behaviours. Here's how it was done:
With Java 8 lambdas, the same job can be done much more succinctly:
Simplifying the Job: Standard Functional Interfaces
Why create a new interface when one already exists? Java’s standard library offers several functional interfaces for common use-cases. So, always check java.util.function
before creating a new interface.
Here's an example of standard interface usage with a custom comparator:
Here, Comparator<T>
is acting as a functional interface.
Light and Breezy: Method References
In scenarios where the lambda expression directly calls a method without any additional logic, we can use method references for brevity. Consider the following lambda:
Now, the method reference:
We use the println
method directly, streamlining the code.
Advantages of Lambdas over Anonymous Classes: Top Trumps!
Lambdas have some advantages over anonymous classes:
- Conciseness and readability: Lambdas are, generally, more compact and transparent.
- Scope and closures: Lambdas can capture effectively final variables without the boilerplate.
- API Friendliness: APIs in Java expect functional interfaces, aiming for lambdas for streamlined use.
However, anonymous inner classes are still effective for complex scenarios that require a full class body.
Ensuring Harmony: Lambda's and Functional Interfaces
The correct use of lambdas depends on understanding their signatures. The parameters and return type of the lambda should match the singular abstract method of the functional interface. Here's an example with a custom functional interface:
Let's Get Groovy: Flexibility of Functional Programming
The use of lambdas and functional interfaces allows for easy manipulation of different behaviors. Unlike traditional object-oriented programming (where several classes would be needed for polymorphic behavior), functional programming in Java allows you to pass different lambdas where the same functional interface is expected.
Putting It All Together: Practical Usage
Make use of standard interfaces
Build an event handler
This replaces an anonymous class implementing an event listener interface.
Avoiding repetition
When the same logic repeats with slight variations, abstract the common logic and vary it with lambdas:
Here, commonLogic
encapsulates the common code, while the andThen
method adds the unique code.
Was this article helpful?