In Kotlin classes, val and var are used to declare properties.
valmeans read-only after initializationvarmeans mutable / can be reassigned
Basic example
class User {
val id: Int = 1
var name: String = "Alice"
}
Usage:
fun main() {
val user = User()
println(user.id) // 1
println(user.name) // Alice
user.name = "Bob" // OK: name is var
// user.id = 2 // Error: id is val
}
val inside a class
Use val when the property should not be reassigned after it gets a value.
class Product {
val sku: String = "ABC-123"
}
You can read it:
val product = Product()
println(product.sku)
But you cannot assign a new value:
// product.sku = "XYZ-999" // Not allowed
var inside a class
Use var when the property can change.
class Counter {
var count: Int = 0
fun increment() {
count++
}
}
Usage:
fun main() {
val counter = Counter()
counter.increment()
counter.increment()
println(counter.count) // 2
}
Declaring properties in the constructor
A common Kotlin style is to put properties directly in the class constructor.
class User(
val id: Int,
var name: String
)
This creates a class with:
- a read-only
id - a mutable
name
Usage:
fun main() {
val user = User(1, "Alice")
println(user.id)
println(user.name)
user.name = "Bob" // OK
// user.id = 2 // Error
}
Important distinction
If you write this:
val user = User(1, "Alice")
The variable user itself cannot point to another User, because it is a val.
But if the object has var properties, those properties can still change:
val user = User(1, "Alice")
user.name = "Bob" // OK, because name is var
// user = User(2, "Charlie") // Error, because user is val
So:
val user
means the reference cannot be reassigned.
var name
inside the class means the property can be changed.
Rule of thumb
Use val by default, and only use var when the value really needs to change.
class Person(
val birthYear: Int,
var displayName: String
)
Here, birthYear probably should not change, but displayName might.
