Can lambda expressions be used with custom functional interfaces?
Answer:
Explanation:
Lambda expressions can be used with any functional interface, including custom ones, as long as the interface has only one abstract method. Custom functional interfaces allow developers to define their own specific behaviors and use them in a more concise way through lambda expressions. Here is an example of a custom functional interface:
@FunctionalInterface interface MyFunction { void apply(int x); } MyFunction printDouble = x -> System.out.println(x * 2); printDouble.apply(5); // Prints: 10
In this example, the custom functional interface MyFunction
is defined, and a lambda expression is used to implement its apply
method. This demonstrates how lambda expressions can be applied to any functional interface, not just those provided by the standard Java library.
Creating custom functional interfaces opens up a wide range of possibilities for developers, allowing them to define reusable, type-safe functions that can be passed around and executed dynamically. This is especially useful in large and complex applications where flexibility and code reuse are essential.