With data
modifier, you can easily create data holder class with Kotlin.
data class User(val name: String, val age: Int)
You can instantiate the data class like this:
val person = User("Mohandas Karamchand Gandhi", 78)
Because declared with val
, these properties could not be reassigned.
person.age = 79 // syntax error
So you may want to change val
to var
, like this.
data class User(val name: String, var age: Int) // unsafe
But this is not safe, because the value may be changed from anywhere.
So in this case, using copy
from data class is safer. With named arguments with copy
you can update data class properties.
var person = User("Mohandas Karamchand Gandhi", 78)
person = person.copy(age = 79)
Top comments (0)