Kotlin从具有子类型的接口覆盖属性

时间:2018-08-01 07:13:26

标签: interface kotlin override subtype

我有以下情况:

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>()

2 个答案:

答案 0 :(得分:0)

要回答您的问题,我首先需要解释它的工作原理。
定义时

interface NiceInterface {
  var currentState: AbstractState
  ...
}

Kotlin为您提供的服务基本上是定义两个方法,在伪Java中看起来可能像这样:

interface NiceInterface {
   AbstractState getCurrentState();
   void setCurrentState(AbstractState state);
}

您要执行的操作是重载具有相同签名但返回类型不同的方法:

interface NiceInterface {
   @Override
   SubState getCurrentState();
   ...
}

显然这是不可能的。

您没有指定用例,但我可能从您的示例中假定您真正在寻找的是属性委托:https://kotlinlang.org/docs/reference/delegated-properties.html

答案 1 :(得分:0)

正如阿列克谢·罗曼诺夫(Alexey Romanov)所说的setter问题,因此有一种解决方法,将var替换为val:

interface AbstractState {}
class SubState : AbstractState{}

interface NiceInterface {
    val currentState: AbstractState
}

class Class : NiceInterface {
    override val currentState: SubState by lazy {
        SubState()
    }
}

所以现在您不需要强制转换:

currentState.doSomething()