语句 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"));

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

有人可以解释它是如何工作的以及它是关于什么的吗?

原文由 sdfsd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 807
2 个回答

你的 陈述拉姆达

param -> { return expression; }

可以更改为 表达式 lambda

 param -> expression

很简单,不是吗?请注意,需要删除大括号和分号。

原文由 Seelenvirtuose 发布,翻译遵循 CC BY-SA 4.0 许可协议

有时我发现如果代码块足够长,将大括号留在原处很有用(我认为这提高了可读性)

在 Android Studio 中,您可以在方法开始时使用 //noinspection CodeBlock2Expr 在本地禁用警告,如下例所示

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

原文由 MatPag 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题