Kotlin 是否支持成员密封覆盖?

时间:2021-07-13 19:57:20

标签: kotlin

在 Kotlin 中,我们可以用 sealed 修饰符修改一个类,以表示该类只能在同一模块内扩展;或来自docs

<块引用>

密封类和接口代表受限制的类层次结构,提供对继承的更多控制。密封类的所有子类在编译时都是已知的。编译带有密封类的模块后,不得再出现其他子类。例如,第三方客户无法在他们的代码中扩展您的密封类。因此,密封类的每个实例都有一个有限集合中的类型,该集合在编译此类时是已知的。

我想知道的是,是否可以将相同或相似的行为应用于类成员;例如,考虑以下代码。所有的类和接口都存在于同一个模块中:

// I don't want to seal this because it should be implementable beyond this module.
interface Hashable {
    val hash: Hash
}

// I don't want to seal this because it should be extensible beyond this module.
abstract class Base : Hashable {
    final override val hash: Hash get() = hashOf(...)
}

open class Derived : Base {

    // This doesn't work because it's final in the base class.
    final override val hash: Hash get() = hashOf(...)
}

我本质上想表达的是,“我(开发人员)确定 Base 应该如何创建它的哈希,直到我(开发人员)在派生类中声明其他方式。此模块之外的其他人没有改变 Base 的每个扩展名或派生类如何创建其哈希的能力。”

这可能吗?

1 个答案:

答案 0 :(得分:1)

您可以创建具有 internal 可见性的其他属性:

abstract class Base : Hashable {
    final override val hash: Hash get() = _hash
    internal open val _hash: Hash get() = hashOf(...)
}

open class Derived : Base() {
    override val _hash: Hash get() = hashOf(...)
}
相关问题