Var Could Be Val

ID

kotlin.var_could_be_val

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

Kotlin

Tags

immutability, style

Description

Reports a function-local var declaration whose value is never reassigned after initialisation. Replacing var with val communicates that the binding is immutable, prevents accidental mutation, and eliminates an entire class of subtle bugs.

Rationale

Kotlin provides val and var as first-class language features precisely to make mutability explicit. When a binding is declared var but the value is never changed, the developer has missed an opportunity to encode intent. Readers must mentally track whether the variable might change; the compiler cannot infer or warn about this without the rule. Using val by default and promoting to var only when needed is idiomatic Kotlin.

// Bad — x is never changed after assignment
fun compute(): Int {
    var x = 5
    return x + 1
}

// Good — communicates immutability
fun compute(): Int {
    val x = 5
    return x + 1
}

// OK — y is reassigned, var is warranted
fun counter(): Int {
    var y = 0
    y += 1
    return y
}

Remediation

Change var to val for any local declaration that is never reassigned after its initialiser. If the compiler then rejects a later assignment you had not noticed, fix that assignment too or keep var.