我的课程类似于以下内容。在第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
块来初始化属性而不进行实例化,所以如果我用init
替换setEditor(getDefaultEditor())
块内的代码,那么编译器会抱怨,“财产必须初始化或抽象”。如何避免重复init
内的所有内容?
答案 0 :(得分:0)
我不知道是否可以显式调用init块。
但我认为这应该适合你:
object MyClass {
var editor: Editor = getDefaultEditor()
set(value) {
field = value
init()
}
lateinit var project: Project
lateinit var document: String
lateinit findModel: FindModel
lateinit var findManager: FindManager
init {
init()
}
private fun init() {
project = editor.project!!
document = editor.document.charsSequence.toString().toLowerCase()
findModel = FindManager.getInstance(project).findInFileModel.clone()
findManager = FindManager.getInstance(project)
}
}
但更好的设计就是这样:
object MyClass {
var editor: Editor = getDefaultEditor()
fun getProject() = editor.project!!
fun getDocument() = editor.document.charsSequence.toString().toLowerCase()
fun getFindModel() = FindManager.getInstance(getProject()).findInFileModel.clone()
fun getFindManager() = FindManager.getInstance(getProject())
}