Java 语句 lambda 可以替换为表达式 lambda
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46238702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Statement lambda can be replaced with expression lambda
提问by sdfsd
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
.
但是,IntelliJ
正在为我的灰色着色return
,但是当我删除return
它时,它向我强调没有return
.
Could someone explain how it works and what is it all about?
有人可以解释它是如何工作的以及它是什么吗?
采纳答案by Seelenvirtuose
Your statement lambda
你的声明 lambda
param -> { return expression; }
can be changed to an expression lambda:
可以更改为表达式 lambda:
param -> expression
Simple, isn't it? Note, that the curly brackets and the semicolon need to be removed.
很简单,不是吗?请注意,需要删除大括号和分号。
回答by MatPag
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
在 Android Studio 中,您可以在//noinspection CodeBlock2Expr
方法开始时使用本地禁用警告,如下例所示
//noinspection CodeBlock2Expr
button.setOnClickListener((View v) -> {
//a long single method call...
});