我有一个看起来像下面这样的类。在第 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/