Looking for ideas on how to do this (or anything vaguely similar) with less boilerplate:
Copy code
interface HasName {
val name: String
fun copy(name: String = name) // boilerplate (but only once)
}
data class Person(
override val name: String,
val age: Int
) : HasName {
override fun copy(name: String = name) // boilerplate (in everything that extends HasName)
}
// Because I want to do this:
val named: HasName = Person(...)
named.copy(name = "newName")
j
Joffrey
02/02/2022, 2:03 AM
I don't see an implementation for
copy
anywhere. Is the implementation of that method supposed to be different in different implementations of
HasName
? What "boilerplate" are you trying to get rid of exactly?
j
jeff
02/02/2022, 2:05 AM
Person already has a copy(name=) by virtue of being a data class. But I need to "re-" define it so that the interface can see it
jeff
02/02/2022, 2:05 AM
(I understand why, just looking for other options)
h
hfhbd
02/02/2022, 9:57 AM
I use a sealed interface and a extension
fun HasName.copy(...) = with (this) { is Person -> copy(...) }