Could Be Sequence
ID |
kotlin.could_be_sequence |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Kotlin |
Tags |
efficiency |
Description
Reports long chains of eager collection operators applied to a Collection.
Operators such as filter, map, flatMap, take, drop, distinct, and
sortedBy each allocate a fresh List holding their result. A chain of N
such operators allocates N intermediate lists; lifting the receiver into a
Sequence defers evaluation and runs the entire pipeline in a single pass
with no intermediate allocations.
The threshold is configurable via properties.minChainLength (default: 4).
Rationale
// FLAW — four chained collection operators allocate three intermediate Lists
xs.filter { it > 0 }
.map { it + 1 }
.filter { it < 10 }
.distinct()
// OK — single pass, no intermediate Lists
xs.asSequence()
.filter { it > 0 }
.map { it + 1 }
.filter { it < 10 }
.distinct()
.toList()
For short chains the allocation overhead is negligible; the rule deliberately
only fires beyond minChainLength operators where the saving becomes
measurable.
Remediation
Insert .asSequence() between the collection and the first operator, and
materialise the result with .toList() (or another terminal operator) at
the end of the chain.