在 kotlin 中从构造函数调用抽象方法是否安全?

Kan*_*anj 3 android android-custom-view kotlin

我正在开发一个 android 项目。我想用抽象方法创建 FrameLayout 的抽象子类

@LayoutRes    
abstract fun getLayoutToInflate(): Int
Run Code Online (Sandbox Code Playgroud)

在构造函数中,我想膨胀此方法返回的布局。但是 IDE 在此代码中显示了有关“在构造函数中调用非最终函数...”的警告

val inflater = LayoutInflater.from(context)
inflatedBanner = inflater.inflate(getLayoutToInflate(), this, true)
Run Code Online (Sandbox Code Playgroud)

此应用程序尚未构建。所以写了一个像这样简单的kotlin代码来测试。

abstract class Base {
    val text: String
    constructor(text: String) {
        this.text = text
        println(text + getTextSuffix())
    }
    abstract fun getTextSuffix(): String
}

class Derived(text: String) : Base(text) {
    override fun getTextSuffix() = "_"
}

fun main(args: Array<String>) {
    val d = Derived("stuff")
}
Run Code Online (Sandbox Code Playgroud)

这段代码总是打印“stuff_”,这意味着被覆盖的抽象方法在构造函数中可用。我也可以在我的应用程序中依赖这种行为吗?如果不是,那么在 kotlin 中实现这样的东西的正确方法是什么?

Mar*_*nik 5

这里的 Kotlin 与 Java 或大多数其他 OOP 语言没有什么不同。

只要您在方法的契约中明确指出覆盖方法不得访问子类中的任何状态,您就可以安全地从基类的构造函数中调用它们。如果一个类违反了这个规则,它的方法将访问未初始化的状态。