Junior — Middle
What difficulties might arise when passing a lambda expression as an argument in a Java method?
sobes.tech AI
Answer from AI
When passing a lambda expression (functional interface) to a Java method, the following issues may arise:
- Typing: The lambda must match the functional interface expected by the method. Mismatch in signatures will cause a compilation error.
- Side effects: If the lambda contains mutable state, it can lead to unpredictable behavior, especially in a multithreaded environment.
- Exception handling: Lambdas cannot throw checked exceptions unless the interface declares them, which limits error handling.
- Serialization: If the lambda needs to be serializable, special approaches are required, as this is not guaranteed by default.
- Performance: Frequent creation of lambdas can impact performance due to object and closure creation.
Example:
public void process(Runnable action) {
action.run();
}
// Call
process(() -> System.out.println("Hello"));
It is important that the lambda matches the Runnable interface and does not violate the method's expectations.