Unreachable Code
ID |
kotlin.unreachable_code |
Severity |
low |
Remediation Complexity |
auto_fix |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Dead Code |
Language |
Kotlin |
Tags |
dead-code, reliability |
Description
Reports a statement that can never execute because control flow always leaves the enclosing
region before reaching it. The analysis walks the function’s control-flow graph: code becomes
unreachable after an unconditional jump (return, throw, break, continue), after a
never-returning call (exitProcess(…), error(…), TODO(…)), or inside an always-taken
constant branch. Only the first statement of each dead region is flagged.
Rationale
Code that follows an unconditional jump is dead code. It misleads readers who may believe the code does something meaningful, and it typically indicates a logic error (the jump was meant to be conditional) or leftover code from a refactoring.
// Bad — unreachable code after throw
fun divide(a: Int, b: Int): Int {
if (b == 0) {
throw ArithmeticException("divide by zero")
return -1 // FLAW — never reached
}
return a / b
}
// Bad — unreachable code after return
fun first(items: List<Int>): Int {
return items[0]
println("returned") // FLAW — never reached
}
// Good
fun first(items: List<Int>): Int = items[0]
Remediation
Remove the unreachable statement. If it was meant to execute, move the terminating statement after it, or make the terminating statement conditional.