This rule raises an issue when a lambda expression uses block notation while expression notation could be used.
The right-hand side of a lambda expression can be written in two ways:
(a, b) → a + b(a, b)
→ {return a + b;}By convention, expression notation is preferred over block notation. Block notation must be used when the function implementation requires more
than one statement. However, when the code block consists of only one statement (which may or may not be a return statement), it can be
rewritten using expression notation.
This convention exists because expression notation has a cleaner, more concise, functional programming style and is regarded as more readable.
This rule does not flag block-form lambdas in the following cases:
{ and closing } are on different lines, a block form is kept for
readability.query() with a single-parameter lambda — converting such a lambda to an expression form may silently
change overload resolution.MethodHandle.invoke() / MethodHandle.invokeExact() — these are signature-polymorphic methods.
Converting such lambdas to an expression form changes the inferred return type, which can cause a WrongMethodTypeException at
runtime.
entries.forEach(e -> { // Compliant, multiline body
System.out.println(e.getKey() + ": " + e.getValue());
});
// Compliant, expression form would resolve to ResultSetExtractor instead of RowCallbackHandler
jdbcTemplate.query("SELECT id, cnt FROM t", rs -> { map.merge(rs.getLong("id"), rs.getLong("cnt"), Long::sum); });
process(() -> { handle.invokeExact(); }); // Compliant, signature-polymorphic invocation stays void
return statement, replace the code block with the argument expression from the
return statement.return statement, replace the code block with that statement.
(a, b) -> { return a + b; } // Noncompliant, replace code block with expression
(a, b) -> a + b // Compliant
x -> { System.out.println(x+1); } // Noncompliant, replace code block with statement
x -> System.out.println(x+1) // Compliant