kotlin - 如何显式调用对象的 init block ?

标签 kotlin

我有一个看起来像下面这样的类。在第 7 行,我想调用 init直接阻塞,但是如果不使用反射,这似乎是不可能的。

object MyClass {
    var editor: Editor = getDefaultEditor()
        set(value) {
            field = value

            //Todo: figure out how to avoid duplicating init block
            project = editor.project!!
            document = editor.document.charsSequence.toString().toLowerCase()
            findModel = FindManager.getInstance(project).findInFileModel.clone()
            findManager = FindManager.getInstance(project)
        }

    var project: Project
    var document: String
    var findModel: FindModel
    var findManager: FindManager

    init {
        project = editor.project!!
        document = editor.document.charsSequence.toString().toLowerCase()
        findModel = FindManager.getInstance(project).findInFileModel.clone()
        findManager = FindManager.getInstance(project)
    }
}

但我需要 init block 以便在不实例化的情况下初始化属性,所以如果我替换 init 中的代码使用 setEditor(getDefaultEditor()) 阻止,然后编译器会提示,“属性必须被初始化或者是抽象的”。如何避免复制 init 中的所有内容?

最佳答案

您可以使用 lateinit对编译器说“我稍后会初始化该属性”。

lateinit var project: Project
lateinit var document: String
lateinit var findModel: FindModel
lateinit var findManager: FindManager

然后你可以在 init 中省略初始化阻止并随时执行。

来自官方文档的通知:

The modifier can only be used on var properties declared inside the body of a class (not in the primary constructor), and only when the property does not have a custom getter or setter. The type of the property must be non-null, and it must not be a primitive type.

Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn't been initialized.

关于kotlin - 如何显式调用对象的 init block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40967544/

相关文章:

Kotlin - 最终类的扩展

reflection - Kotlin:如何访问委托(delegate)的 get- 和 setValue 方法?

java - Spring 数据 : JPA and Nested Transaction

spring-boot - 在类型 'isLPG' 的对象上找不到属性或字段 'com.rentautosofia.rentacar.bindingModel.CarBindingModel' - 可能不是公共(public)的?

android - 如何避免 Kotlin 中同名冲突的类型?

android - Kotlin 中货币的数据类型

Kotlin Char compareTo 失败

kotlin - 在异步调用完成之前按下后退按钮会发生什么?

java - 在@Transactional方法调用期间,初始化期间Bean属性不为null

当表达式上的 Kotlin 智能转换