Immutability
- Kotlin course
- Advanced
- Lesson 49/83
- 5 min
Learn immutability with val and data class.
Immutability and data class
Immutability means an object does not change after creation. In Kotlin it is achieved with data class and val properties. A data class auto-generates the copy method.
Example: data class User(val name: String, val age: Int). To change a property you call user.copy(age = 31); this returns a new User. The original stays unchanged. This pattern reduces concurrency bugs and makes code more predictable.
The val vs var difference
Variables declared with val are assigned once and cannot be reassigned. var can be reassigned. For immutability, val is preferred.
Example: after val name = "Alex", writing name = "Sam" gives a compile error. var name = "Alex" can be reassigned. In functional style, val is preferred; it reduces side effects and improves readability.
Practice Update age with copy
Define a data class User with properties val name: String and val age: Int. In main create val u = User("Alex", 30), create u2 with u.copy(age = 31) and print println(u2).
Starter code
// User data class: name and age properties
// in main create u, copy with age 31, printSample solution
data class User(val name: String, val age: Int)
fun main() {
val u = User("Alex", 30)
val u2 = u.copy(age = 31)
println(u2)
}Expected output
User(name=Alex, age=31)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method is used to change a property of a data class instance?
- update
- set
- mutate
- copy Correct answer
Explanation: copy returns a new modified instance.
2 Complete the data class definition
____ User(val name: String, val age: Int)
data User(val name: String, val age: Int)
Explanation: data class auto-generates copy and equals.
3 Match the immutability parts
| Term | Meaning |
|---|---|
data class |
Immutable class |
val |
Single assignment |
copy(age=31) |
New object |
var |
Reassignable |