In the end, it is hard to beat the copy constructor for brevity and flexibility.
data class Person(
val name: String,
val address: Address? = null,
val phone: String? = null
)
val jenna = Person("Jenna")
val withMoreData = jenna.copy(
address = Address(...),
phone = "(555) 555-1212"
)
If you want to do something fancy in a “setter”:
fun Person.withAddress(addressString: String) =
copy(address = addressString.toAddress())
Sure but that’s no longer possibel if your data class looks like this
data class Person(
val name: String,
val address: Address,
val phone: String
)
val jenna = error("can't create empty Person")
val withMoreData = jenna.copy(
name = "Jenna",
address = Address(...),
phone = "(555) 555-1212"
)