kotlincopyvardata-classval

Kotlin. Data class: how to update one of the parameters?


I have data class. For example:

  data class Test(
        val data: String,
        val data2: String
    )

Suppose I have a need to change one of the parameters of my data class. For this I will write the following code:

  var test = Test(data = "data", data2 = "data2")
  test = test.copy(data = "new_data")

But at the same time, I can make a parameter var and change it directly:

  data class Test(
            var data: String,
            val data2: String
        )


 var test = Test(data = "data", data2 = "data2")
 test.data = "new_data"

Which method is better to use? Suppose that my data class can have a large number of parameters, will there be any problems in this case when using copy().

Please, help me.


Solution

  • Depends how you're using the class.

    I find it's more common to be using data classes to represent the "latest state" of something, in which case you do not want to be using var with it, because that is error-prone. It prevents you from comparing old and new data, using the class in Sets and as Map keys, etc.

    If they hold a representation of ongoing state (more common in games and simulations), var might be applicable, in which case you'll find you rarely need the copy() function. If you use copy() in this case, you get a new copy without affecting the original.