A return without a label in a forEach lambda returns from the enclosing function, not from the lambda

tx0/kotlin:return-from-for-eachrecommendedwarningreliability/control-flowdepth fastbug

What it finds

items.forEach { if (it.bad) return } leaves the whole function at the first bad item, because forEach is inline and an unlabeled return belongs to the function. A loop continue is written return@forEach. A return with a value is not reported, since it is plainly meant for the function.

From the rule's source, return_in_for_each.rs.

Example from the rule's tests
fun scan(items: List<Int>): Int {    items.forEach {        if (it < 0) returntx0 reports: this return leaves the enclosing function    }    items.forEach {        if (it < 0) return@forEach    }    items.forEach { if (it == 0) return 0 }    items.map { if (it < 0) fun() { return } }    return 1}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/kotlin:return-from-for-each" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/kotlin:return-from-for-each] reason="..."

tx0 explain tx0/kotlin:return-from-for-each shows the same in the terminal. Found a false positive? Report it.