sealed class extends other sealed class
sealed class extends other sealed class
我在使用 MVI 模式时制作各种状态模型和副作用 classes。状态模型可以通过扩展收集公共部分的接口来减少样板,但是副作用class不支持扩展,因为它是一个密封的class。所以我将 Toast 副作用视为样板代码。我怎样才能摆脱这个 Toast 副作用样板代码? sealed class 有没有办法扩展到其他 sealed classes?
我的状态class是:
interface BaseMviState {
val loaded: Boolean
val exception: Exception?
fun isException() = exception != null
}
data class MviJoinState(
override val loaded: Boolean = false,
override val exception: Exception? = null,
val loginResult: Boolean = false,
val registerResult: Boolean = false,
) : BaseMviState
data class MviRoomCreateState(
override val loaded: Boolean = false,
override val exception: Exception? = null,
) : BaseMviState
我的副作用 classes:
sealed class MviJoinSideEffect {
data class SetupAutoLogin(val user: User) : MviJoinSideEffect()
data class Toast(val message: String) : MviJoinSideEffect() // boilerplate
}
sealed class MviRoomCreateSideEffect {
data class Toast(val message: String) : MviRoomCreateSideEffect() // boilerplate
}
我通过在密封 class 中扩展接口解决了这个问题,如下所示:
sealed interface BaseEvent {
data class Toast(val toastMessage: String) : BaseEvent
}
sealed class Event : BaseEvent {
data class Snackbar(val snackbarMessage: String) : Event()
}
fun main() {
val event: BaseEvent = Event.Snackbar("Hi")
when (event) {
is BaseEvent.Toast -> todo(event.toastMessage)
is Event.Snackbar -> todo(event.snackbarMessage)
}
}
fun todo(message: String) {}
我在使用 MVI 模式时制作各种状态模型和副作用 classes。状态模型可以通过扩展收集公共部分的接口来减少样板,但是副作用class不支持扩展,因为它是一个密封的class。所以我将 Toast 副作用视为样板代码。我怎样才能摆脱这个 Toast 副作用样板代码? sealed class 有没有办法扩展到其他 sealed classes?
我的状态class是:
interface BaseMviState {
val loaded: Boolean
val exception: Exception?
fun isException() = exception != null
}
data class MviJoinState(
override val loaded: Boolean = false,
override val exception: Exception? = null,
val loginResult: Boolean = false,
val registerResult: Boolean = false,
) : BaseMviState
data class MviRoomCreateState(
override val loaded: Boolean = false,
override val exception: Exception? = null,
) : BaseMviState
我的副作用 classes:
sealed class MviJoinSideEffect {
data class SetupAutoLogin(val user: User) : MviJoinSideEffect()
data class Toast(val message: String) : MviJoinSideEffect() // boilerplate
}
sealed class MviRoomCreateSideEffect {
data class Toast(val message: String) : MviRoomCreateSideEffect() // boilerplate
}
我通过在密封 class 中扩展接口解决了这个问题,如下所示:
sealed interface BaseEvent {
data class Toast(val toastMessage: String) : BaseEvent
}
sealed class Event : BaseEvent {
data class Snackbar(val snackbarMessage: String) : Event()
}
fun main() {
val event: BaseEvent = Event.Snackbar("Hi")
when (event) {
is BaseEvent.Toast -> todo(event.toastMessage)
is Event.Snackbar -> todo(event.snackbarMessage)
}
}
fun todo(message: String) {}