DEV Community

okuzawats
okuzawats

Posted on • Edited on

How to make your data class properties immutable

With data modifier, you can easily create data holder class with Kotlin.

data class User(val name: String, val age: Int)
Enter fullscreen mode Exit fullscreen mode

You can instantiate the data class like this:

val person = User("Mohandas Karamchand Gandhi", 78)
Enter fullscreen mode Exit fullscreen mode

Because declared with val , these properties could not be reassigned.

person.age = 79 // syntax error
Enter fullscreen mode Exit fullscreen mode

So you may want to change val to var , like this.

data class User(val name: String, var age: Int) // unsafe
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)