Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 754
SMBiggs Avatar asked Dec 05 '25 04:12

SMBiggs


1 Answers

Call the copy function:

morris.copy(fixed = true)

like image 156
Louis Wasserman Avatar answered Dec 12 '25 05:12

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!