Variables — val and var
Kotlin's two ways to declare a variable, and why you should reach for val by default.
읽는 데 2분
Kotlin has exactly two keywords for declaring a variable: val and var. Choosing between them is one of the first habits worth building, because it shapes how predictable your code is.
val: assign once
val declares a read-only reference — you can set it once, and any later attempt to reassign it is a compile error.
val name = "Alice"
name = "Bob" // Compile error: Val cannot be reassigned"Read-only" is more precise than "constant," though. A val holding a mutable object can still have its contents change — you just can't point the variable at a different object:
val scores = mutableListOf(10, 20)
scores.add(30) // fine — the list itself is mutable
scores = mutableListOf(1) // Compile error — scores can't be reassignedvar: assign as many times as you need
var declares a mutable reference, which can be reassigned freely:
var counter = 0
counter = counter + 1
counter += 1
println(counter) // 2Why default to val
Prefer val unless you have a concrete reason a variable needs to change. This isn't a style nitpick — it has real payoffs:
- Fewer bugs. A value that can't change can't be changed unexpectedly by code you forgot about three functions away.
- Easier reasoning. When you read
val total = calculateTotal(), you knowtotalmeans the same thing everywhere below it. Withvar, you have to track every place it might get reassigned. - Safer concurrency. Immutable data can be shared across threads without locks, because nothing can mutate it out from under another thread.
Most Kotlin style guides — and the Kotlin compiler's own IDE inspections — will nudge you to change a var to val whenever it's never actually reassigned:
// IDE will suggest: "Variable is never reassigned, could be val"
var greeting = "Hello" // should be val
println(greeting)Declaring without initializing
You can declare a variable's type without assigning it immediately, as long as you assign it before it's used:
val age: Int
if (hasBirthCertificate) {
age = 30
} else {
age = -1
}
println(age)This still respects val's "assign once" rule — the compiler can prove exactly one of those two branches runs, so exactly one assignment happens.
Once you're comfortable choosing between val and var, the next lesson looks at Kotlin's basic types and how it infers them without you spelling them out every time.