ExpressionOverBlockLambda

Since Checkstyle 14.1.0

Description

Checks that expression lambdas are used instead of single-line block lambdas where possible.

Rationale: According to the OpenJDK Java Style Guidelines (and general modern Java conventions), expression lambdas are preferred over single-line block lambdas for readability and conciseness.

A single-line block lambda is a lambda whose body is a block ({...}) that fits on a single line and contains only one statement that could be written as an expression lambda.

Examples

To configure the check:


<module name="Checker">
  <module name="TreeWalker">
    <module name="ExpressionOverBlockLambda"/>
  </module>
</module>

Example:


public class Example1 {
  public void foo() {
    // violation below 'preferred over single-line'
    Runnable a = () -> { System.out.println("hello"); };

    // violation below 'preferred over single-line'
    Function<Integer, Integer> b = x -> { return x + 1; };

    // ok - expression lambda
    Runnable c = () -> System.out.println("hello");

    // ok - multi-line block lambda
    Runnable d = () -> {
      System.out.println("hello");
    };

    // ok - void return
    Runnable e = () -> { return; };

    // ok - multi-statement block
    Runnable f = () -> {
      System.out.println("hello");
      System.out.println("world");
    };
  }
}

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Fully Qualified Name

com.puppycrawl.tools.checkstyle.checks.coding.ExpressionOverBlockLambdaCheck

Use this fully qualified class name in configuration when an exact class reference is required.

Parent Module

TreeWalker