forEach Unused Value

ID

kotlin.foreach_unused_value

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

reliability, unused-code

Description

Reports collection.forEach { …​ } calls whose lambda body never reads the iteration parameter (the implicit it or an explicitly named one). A forEach whose body ignores the current element is almost always a leftover from a refactor: the developer wanted to run the side effect N times, or they wanted to read the collection’s size — neither of which requires iterating over the elements.

Rationale

xs.forEach { println("hello") }            // FLAW — `it` never read
xs.forEach { v -> println("hello") }       // FLAW — `v` never read

xs.forEach { println(it) }                 // OK
xs.forEach { v -> println(v) }             // OK

Iterating produces the iteration cost; if the body never reads the element, that cost is paid for nothing — and worse, future readers of the code spend time looking for the relationship between the body and the collection elements before realising there isn’t one.

Remediation

Pick the intent that matches the body:

  • repeat(xs.size) { println("hello") } — run a side effect N times.

  • println(xs.size) — read the count once.

  • If the element really is needed, restore the missing reference inside the lambda.

References