Hello guys :slightly_smiling_face: Was looking to ...
# announcements
j
Hello guys 🙂 Was looking to simplify a bit of code I have Looks like this :
Copy code
sealed class Sealed(open val x: Int) {
    data class A(override val x: Int) : Sealed(x)
    data class B(override val x: Int) : Sealed(x)
}

private fun copyTest(test: Sealed, y: Int): Sealed {
    // "standard" way, it works
    return when (test) {
        is Sealed.A -> test.copy(x = y)
        is Sealed.B -> test.copy(x = y)
    }
    // Sadly, this does not
    return test.copy(x = y)
}
Is the when approach the only one? Or am I missing something? Thanks!
l
I dont think it's possible, as the parent Sealed class doesn't declare the
copy
method, it's specific to data classes and thus you need to define it there.
An option is to create a copy method yourself on your base Sealed class