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)

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)

筆者

茨城県つくば市在住のソフトウェアエンジニアです。得意領域はAndroidとFlutterです。「Jetpack ComposeによるAndroid MVVMアーキテクチャ入門」の著者です。

👉もっと詳しく