如何正确覆盖 Kotlin 类中的 var?

Mah*_*kus 3 inheritance android class kotlin

我正在尝试覆盖类中的值。我有以下代码:

open class Balloon() {
    open var textSize: Float = 20f
    init {
        Log.i("textSize", textSize.toString())
    }
}
    
class BigBalloon(): Balloon() {
    override var textSize = 30f
}
Run Code Online (Sandbox Code Playgroud)

但是,日志会打印出这些值:

在此处输入图片说明

第一个日志来自Balloon(),第二个来自BigBalloon()0.0当我将其覆盖为 时,它如何打印30?我是否错误地实施了所有这些?

Paw*_*wel 5

getTextSize通常不鼓励在构造函数中访问抽象方法(在这种情况下),因为它可能会导致像您这样的工件。

BigBaloon 属性覆盖实际上做了两件事:

  1. 创建新的内部字段 - BigBaloon.textSize
  2. 覆盖textSizegetter 和 setter 以访问该字段

这有点反直觉,但它不会修改Baloon.textSize字段的值,由于 getter/setter 不再使用它,因此它保持不变且无法访问。

您的问题是当BigBaloons parentBaloon被初始化时,它会访问BigBaloon.textSize此时未初始化的对象,因此它返回零。