Back to Intellij Community

ForEachWithRecordPatternCanBeUsed

java/java-impl/resources/inspectionDescriptions/ForEachWithRecordPatternCanBeUsed.html

2025.3-rc-21.1 KB
Original Source

Reports local variable declarations and accessors to record components that can be replaced with pattern variables in enhanced for statements, which are usually more compact.

Example:

record Record(Integer x, String y) {
}

public static void test(List<Record> records) {
    for (Record record : records) {
        System.out.println(record.y());
        Integer x = record.x;
        System.out.println(x);
    }
}

Can be replaced with:

record Record(Integer x, String y) {
}

public static void test(List<Record> records) {
    for (Record(Integer x, String y) : records) {
        System.out.println(y);
        System.out.println(x);
    }
}
  • Use the Nesting depth limit option to specify the maximum number of nested deconstruction patterns to report
  • Use the Maximum number of record components to deconstruct option to specify the maximum number of components, which a record can contain to be used in deconstruction patterns
  • Use the Maximum number of not-used record components option to specify the maximum number of components, which are not used in for statement

New in 2023.1