Statement lambda can be replaced with expression lambda

JavaSpringSpring MvcLambdaOptional

Java Problem Overview


I do user and invitation validation using the Optional facility

@DeleteMapping("/friends/{username}")
public
HttpEntity<Boolean> removeFriend(
        @ApiParam(value = "The user's name", required = true) @PathVariable String username
) {
    Long fromId = authorizationService.getUserId();

    return userService.findByUsername(username)
            .map(user -> {
                 return friendshipService.findFriendship(fromId, user.getId())
                        .map(friendship -> {
                            friendshipService.removeFriendship(friendship);

                            friendship.setToId(friendship.getFromId());
                            friendship.setFromId(friendship.getToId());

                            friendshipService.removeFriendship(friendship);

                            return ResponseEntity.ok(true);
                        }).orElseGet(() -> ResponseEntity.notFound().build());
            }).orElseThrow(() -> new ResourceNotFoundException("User not found"));

However, IntelliJ is colouring my grey return, But when I remove the return, it highlights to me that there is no return.

Could someone explain how it works and what is it all about?

Java Solutions


Solution 1 - Java

Your statement lambda

param -> { return expression; }

can be changed to an expression lambda:

param -> expression

Simple, isn't it? Note, that the curly brackets and the semicolon need to be removed.

Solution 2 - Java

> Sometimes I found useful to leave the > braces where they are if the block of code is long enough (I think it improves readability)

In Android Studio you can locally disable the warning using //noinspection CodeBlock2Expr at the start of the method like in the example below

//noinspection CodeBlock2Expr
button.setOnClickListener((View v) -> {
        //a long single method call...
});

Solution 3 - Java

The Statement lambda can be replaced with expression lambda message appears when we use curly braces "{}" and semicolons ";" in expression lambdas for implementing functional interfaces. We can do away with those in such a situation. That being said, I personally feel it is a good coding practice to use block lambdas even for single line functional interface implementations, the way we do it for single line for and while loops.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsdfsdView Question on Stackoverflow
Solution 1 - JavaSeelenvirtuoseView Answer on Stackoverflow
Solution 2 - JavaMatPagView Answer on Stackoverflow
Solution 3 - JavaNachiket DokeView Answer on Stackoverflow