Replies: 2 comments 3 replies
-
@Darshanbc You're correct that default methods in functional interfaces cannot be overridden using lambda expressions, as lambdas can only target the single abstract method of a functional interface. This is a design limitation in Java. To address your specific use case, while avoiding redundancy or bloating the codebase with multiple interfaces, you can use an anonymous class to provide an implementation for the onMessage(Collection<Message> messages) method alongside the lambda for the single message handling: MessageListener<String> listener = new MessageListener<>() {
@Override
public void onMessage(Message<String> message) {
System.out.println(message.getContent());
}
@Override
public void onMessage(Collection<Message<String>> messages) {
messages.forEach(msg -> System.out.println(msg.getContent()));
}
}; This approach avoids creating multiple interfaces while giving you flexibility to override the onMessage method for batch processing. Java's current lambda behavior only targets the single abstract method (SAM) in a functional interface, so a direct workaround isn't possible without changes to the API design. @FunctionalInterface
public interface MessageListener<T> {
void onMessage(Message<T> message);
default void onMessage(Collection<Message<T>> messages) {
messages.forEach(this::handleSingleMessage);
}
default void defaultBehaviour(Message<T> message) {
throw new UnsupportedOperationException("Single message handling not implemented");
} CC : @maciejwalkowiak |
Beta Was this translation helpful? Give feedback.
-
Hi @Darshanbc and @shreyas957. Yup, you're both correct. This was a design decision - we could have separate interfaces for batch and single message operations, but that would mean double the amount of interfaces, and as @Darshanbc pointed out, this would bloat the codebase. As @shreyas957, there are a number of strategies to mitigate this in a more lambda-friendly way for batch operations, so IMO the current approach is appropriate. Would you both agree, or is there any other strategy we could look into? |
Beta Was this translation helpful? Give feedback.
-
Currently, in Java, default methods in functional interfaces cannot be overridden using lambda expressions. While functional interfaces are designed to simplify code using lambdas, default methods are excluded from this flexibility.
If I want to override the
onMessage(Collection<Message<T>> messages)
method using a lambda, the following code is invalid
Solution:
Have Separate Functional Interfaces:
Define separate interfaces for single and batch processing. However, this creates redundancy and bloats the codebase.
Beta Was this translation helpful? Give feedback.
All reactions