Kotlin:未经检查的演员阵容:将班级分类给它的儿童班(通用)。怎么预防?

时间:2018-05-02 14:30:41

标签: kotlin

我在\Z上有when,我用它来检查它是否属于某个类,我会使用这些数据。它具有通用seal class,如下所示。

T

代码有效。但是,它会对sealed class State object Empty : State() class Load<T>(val presentable: Presentable<T>) : State() class Data<T>(val presentable: Presentable<T>) : State() class LoadableContentController<T>( private val presenter: LoadableContentPresenter<T>) { private var state: State = Empty fun present(content: Presentable<T>?) { this.state = if (content == null) { Empty } else { Data(content) } this.performSideEffects() } private fun performSideEffects() { when (this.state) { is Data<*> -> { presenter.present((state as Data<T>).presentable) } is Load<*> -> { presenter.present((state as Load<T>).presentable) } } } } interface LoadableContentPresenter<T> { fun present(presentable: Presentable<T>) } interface Presentable<T> { val TAG: String fun createView(): () -> T } 提出以下建议。

Unchecked cast: State to Load<T>

有没有办法阻止警告,或者发生自动投射(所以我不需要投射它)?

1 个答案:

答案 0 :(得分:3)

您应该简单地使基类通用:

sealed class State<out T>
object Empty : State<Nothing>()
class Load<T>(val presentable: Presentable<T>) : State<T>()
class Data<T>(val presentable: Presentable<T>) : State<T>()

在你的班上:

class LoadableContentController<T>(
        private val presenter: LoadableContentPresenter<T>) {

    private var state: State<T> = Empty

    private fun performSideEffects() {
        val state = this.state
        when (state) {
            is Data<T> -> {
                presenter.present(state.presentable)
            }
            is Load<T> -> {
                presenter.present(state.presentable)
            }
        }
    }
}