Interface kotlin从具有子类型的接口重写属性

Interface kotlin从具有子类型的接口重写属性,interface,kotlin,overriding,subtype,Interface,Kotlin,Overriding,Subtype,我有以下情况: interface AbstractState {...} interface SubState {...} interface NiceInterface { var currentState: AbstractState ... } 此外,我还有一个实现这个接口的类 class Class : NiceInterface { override var currentState: AbstractState = SubState() } 这意味着我必须在课堂上

我有以下情况:

interface AbstractState {...}
interface SubState {...}

interface NiceInterface {
  var currentState: AbstractState
  ...
}
此外,我还有一个实现这个接口的类

class Class : NiceInterface {
  override var currentState: AbstractState = SubState()
}
这意味着我必须在课堂上每次使用它时写以下内容:

(currentState as SubState).doSomething()
有没有办法避免“作为子状态”部分?或者某种聪明的方法来做这件事?

与泛型一样:

interface => val currentStates: List<out AbstractState>
class     => override val currentStates = ArrayList<SubState>()
interface=>val当前状态:列表
class=>override val currentStates=ArrayList()

正如Alexey Romanov所说,setter存在问题,因此有一个解决方法,用val替换var:

interface AbstractState {}
class SubState : AbstractState{}

interface NiceInterface {
    val currentState: AbstractState
}

class Class : NiceInterface {
    override val currentState: SubState by lazy {
        SubState()
    }
}
所以现在你不需要投:

currentState.doSomething()

相关:(tl;上面的答案说你做错了)