Unconditional Jump In Loop

ID

kotlin.unconditional_jump_in_loop

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

correctness, reliability

Description

Reports loops whose first body statement is an unconditional return, break, or throw, causing the loop to exit after processing at most one element. The loop construct serves no purpose and the pattern is almost always a bug.

Rationale

A loop exists to process multiple elements or iterate until a condition is met. When the loop body unconditionally jumps out on the first pass, the loop is equivalent to a plain if (collection.isNotEmpty()) check followed by processing a single element.

// Bad — loop never runs more than once
fun firstItem(items: List<Int>): Int {
    for (item in items) {
        return item         // always exits on first element
    }
    return -1
}

// Good — conditional exit
fun findFirst(items: List<Int>): Int? {
    for (item in items) {
        if (item > 0) return item    // conditional
    }
    return null
}

// Good — no loop needed
fun firstItem(items: List<Int>): Int = items.firstOrNull() ?: -1

Remediation

Either make the jump conditional so the loop can actually iterate, remove the loop and use the appropriate collection function (firstOrNull, first, find, etc.), or replace the loop with a direct index access if only the first element is needed.