Statement lambda can be replaced with expression lambda

44,190

Solution 1

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

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...
});
Share:
44,190
sdfsd
Author by

sdfsd

Updated on December 31, 2020

Comments

  • sdfsd
    sdfsd over 3 years

    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?

  • sdfsd
    sdfsd over 6 years
    Works. Thanks. Which in your opinion is a better way to lambda this pastebin.com/imEtjwHp or this pastebin.com/gcaUMYQ4?
  • Seelenvirtuose
    Seelenvirtuose over 6 years
    There is no better in this context. Do it as you like. But for me, both code snippets are not readable. This should always be the first criterion for coding.
  • mochadwi
    mochadwi over 4 years
    @Seelenvirtuose would you mind giving us an example for the readable code snippets?