Search code examples
javalambdajava-8anonymous-class

how to write lambda expression for the abstract class


I have abstract class which have two methods as follows:

public abstract class SessionExecutionBody {
   public Object execute() {
     executeWithoutResult();
     return null;
   }

   public void executeWithoutResult() {}
} 

and I implement the class as follows:

final HTTPDestination destination = sessionService.executeInLocalView(new SessionExecutionBody() {
            @Override
            public Object execute() {
                userService.setCurrentUser(userService.getAdminUser());
                final String destinationName = getConfigurationService().getConfiguration().getString(DESTINATION_PROPERTY);
                return getHttpDestinationService().getHTTPDestination(destinationName);

When I run sonarLint its showing major issue convert this anonymous class to lambda expression but I am unable to find the way to right the same , Can I convert that expression into a lambda?


Solution

  • I'm afraid you can't. That is not a functional interface with one abstract method to implement it in the lambda style.

    Can I convert that expression into a lambda?

    You could if you make the following changes:

    @FunctionalInterface // to guarantee the next rule
    interface SessionExecutionBody {
        Object execute(); // has exactly one abstract method
    
        default void executeWithoutResult() {} // other methods should be default/static
    }
    ...
    sessionService.executeInLocalView(() -> { /* a body */ return ...; })