87

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?

4 Answers 4

181

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Works. Thanks. Which in your opinion is a better way to lambda this pastebin.com/imEtjwHp or this pastebin.com/gcaUMYQ4?
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.
@Seelenvirtuose would you mind giving us an example for the readable code snippets?
5

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

Comments

1

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.

Comments

0

Reports lambda expressions with code block bodies when expression-style bodies can be used instead. The result of the conversion is shorter and more clear.

Example:

Comparable<String> c = o -> {return 0;}; 

After the quick-fix is applied:

Comparable<String> c = o -> 0; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.