Variables in Kotlin come in two flavors: val and var. And once you understand the difference, you'll write safer code without even thinking about it.
val โ read-only (immutable)
A val can only be assigned once. Think of it as a constant โ once you set it, it's locked.
fun main() {
val name = "Alice"
println(name)
// name = "Bob" // This would cause an error!
}
Use val by default. Your future self will thank you.
var โ mutable
A var can be changed as many times as you want. Use it when you really need a value to change.
fun main() {
var score = 0
println(score)
score = 10
println(score)
score = score + 5
println(score)
}
Type inference is real
Notice I didn't tell Kotlin that name is a String or score is an Int. Kotlin figures it out from the value you assign. That's called type inference.
You can still be explicit if you want:
fun main() {
val name: String = "Alice"
var score: Int = 0
println("$name has $score points")
}
Naming rules
- Can contain letters, numbers, and underscores
- Must start with a letter or underscore
- Are case-sensitive (so
nameandNameare different) - Use camelCase by convention:
myVariableName