Is there an other way besides duplication to solve...
# getting-started
p
Is there an other way besides duplication to solve the below problem? I have a sealed interface with multiple concrete types (implemented as data classes) that have common properties but also custom ones per type. When I want to update an object of the sealed interface type I need to update the common propertes in each branch of the when - block because the interface type has no copy - constructor. Is there no better way to update the common properties? Below you can see a simplified version. The real code has a lot more properties that needs to be updated.
Copy code
sealed interface Foo {
    val name: String
}

data class Bar(override val name: String, val age: Int) : Foo

data class Baz(override val name: String, val eyeColor: String) : Foo

data class Bit(override val name: String, val salary: Double) : Foo


fun main() {
    val newName = "New Name"
    val updatedFoo = when (val foo = getFoo()) {
        is Bar -> {
            foo.copy(
                name = newName,
                age = 15,
            )
        }

        is Baz -> {
            foo.copy(
                name = newName,
                eyeColor = "blue",
            )
        }
        is Bit -> {
            foo.copy(
                name = newName,
                salary = 2.499
            )
        }
    }
    println(updatedFoo)
}
s
You could try nesting all the common properties inside their own data class
y
Define your own
copy
method with default arguments in the sealed interface, and implement it in each class. You'd then end up doing 2 copies, which isn't going to be that expensive I don't think.