语句 lambda 可以替换为表达式 lambda

我使用可选工具进行用户和邀请验证

@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"));

然而,IntelliJ的颜色是我的灰色 return,但当我删除的 return,它突出了我,有没有 return

有人能解释一下它是怎么运作的吗?

48332 次浏览

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.

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...
});

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.