kotlin - 为什么我们应该避免使用基类的开放成员?

标签 kotlin

当我正在阅读document时对于 Kotlin,我发现我们应该避免使用在基类中声明的 open 属性:

It means that, by the time of the base class constructor execution, the properties declared or overridden in the derived class are not yet initialized. If any of those properties are used in the base class initialization logic (either directly or indirectly, through another overridden open member implementation), it may lead to incorrect behavior or a runtime failure. When designing a base class, you should therefore avoid using open members in the constructors, property initializers, and init blocks.

文档说,当调用基类的构造函数时,派生类中的属性尚未初始化。但是,我们如何从基类构造函数访问派生类未初始化的属性(我假设不正确的行为或运行时失败是由这种情况引起的)?可能吗?

最佳答案

我不懂 kotlin,但我假设 open 与其他语言中的 virtual 相同。在基类构造函数中调用虚拟成员是不安全的,因为基类构造函数是在派生构造函数之前调用的。如果重写的属性要求派生类完全初始化,则可能会导致错误,因为当您位于基构造函数内时尚未调用派生构造函数。至少在 C# 等 .NET 语言中是这样的。

关于kotlin - 为什么我们应该避免使用基类的开放成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603300/

相关文章:

kotlin - Gitlab CI Pipeline - Selenium 服务无法连接到主机

android - Kotlin/Native-> androidMain->无法解析的符号

Kotlin:withContext() 与 Async-await

kotlin - 如何将可变集合变成不可变集合

java - 重复类 Koin org.koin 和 io.insert-koin

java - 由于 Kotlin 中未解析的引用,无法设置文本或可绘制对象

android - 为什么 Kotlin for Android Developers(该书)需要再次添加扩展 parseList?

java - Kotlin - Spring REST - 不会调用带有 ExceptionHandler 的 ControllerAdvice

android - Kotlin 属性访问语法如何适用于 Java 类(即 EditText setText)?

android - @Parcelize 在多平台项目中