Problem Statement
Explain the difference between val and var with examples and when to use each.
Explanation
Use val for read-only variables that are assigned once and never change, like val pi equals 3.14 or val name equals John, which is similar to final in Java and promotes immutability making code safer and more predictable. Use var for mutable variables that need to be reassigned, like var counter equals 0 followed by counter plus plus, necessary for loops, accumulators, or state that legitimately changes. Prefer val as the default choice and only use var when you genuinely need to mutate the variable, as immutability prevents accidental changes, makes code easier to reason about especially in concurrent environments, and aligns with functional programming principles. The Kotlin style guide recommends using val whenever possible, and the IDE even suggests converting var to val when it detects the variable is never reassigned, helping enforce this best practice.
