kotlinobject-construction

Kotlin: How do you make a new instance of a data class with changes


I have a kotlin data class:

data class MyCats (
) {
    val name: String = "",
    val female: Boolean = false,
    val fixed: Boolean = false
}

As I understand Kotlin (still a newbie), I can instantiate this class and set all its parameters at once, such as

val morris = MyCats("Morris")

Now let's say that I get morris fixed. I can't change the value of morris.fixed because it's a val. But I can create a new object. How do I make a new object with all the values of morris, but with the fixed set to true?

Sure, I could go through and do everything manually, but I thought the whole point of Kotlin was to save programmers from that sort of boilerplate code.


Solution

  • Call the copy function:

    morris.copy(fixed = true)