Chaining list(s) to a list literal via addAll
, e.g. [42]..addAll(l1)..addAll(l1);
, is both less efficient and less
verbose than using a list literal with the spread operator: [42, ...l1, ...l1]
.
-
addAll
chains can be less efficient because each addAll
call is treated as a separate method call, resulting in
unnecessary invocations and allocations, when the goal is to build a single list with all the items provided as arguments
-
addAll
chains are generally more verbose and less clear because spreading a list can be done via dedicate syntax
(...
) which is closer to natural language
The rule also applies when the chained list is a conditional expression,
because the spread operator can be applied conditionally:
[42]..addAll(i1 == i2 ? [43, 44] : []); // Noncompliant
[42, if (i1 == i2) ...[43, 44]]; // Compliant
Exceptions
The rule doesn’t apply when the list chained is a literal, because S7089 already covers this case.
[]..addAll([42]); // Not applicable
The rule doesn’t cover if and for collections either, for the same
reason (S7089 covers it).
[42]..addAll([if (i1 == 42) 43, 44]); // Not applicable
[42]..addAll([for (final i in [1, 2, 3]) i * i]); // Not applicable
The rule doesn’t apply when the addAll
is not called via cascade operator, but via standard dereference (.
):
[].addAll(l1); // Not applicable
[]..addAll(l1); // Noncompliant