tschuchort
09/18/2017, 12:56 PMcopy
function to use immutability, but it gets quite annoying when you have two data classes which extend the same base class and you have to "copy" the common fields manually. When using the new MVI-architecture on android, you represent the different states of your app as data classes in a sealed class hierarchy and often times the data classes share many common fields or even only differ in their name, so this would remove a lot of bloat for many people.
I propose that the compiler generates a "copy" method for every non-interface superclass that initializes the common fields:
sealed class State {
abstract val a: Int
data class Default(override val a: Int, val b: Int = 0) : State() {
companion object {
// generated method
fun copy(sup: State, a: Int = sup.a, b: Int = 0) = Default(a, b)
}
}
data class Loading(override val a: Int, val c: Int = 0) : State() {
companion object {
// generated method
fun copy(sup: State, a: Int = sup.a, c: Int = 0) = Loading(a, c)
}
}
}
so when transitioning from Default
to Loading
state you just write newState = Loading.copy(oldState, 0)
I think it would be pretty easy to implement, maybe as a compiler plugin