如何显式调用对象的init块?

时间:2016-12-05 05:18:45

标签: 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块来初始化属性而不进行实例化,所以如果我用init替换setEditor(getDefaultEditor())块内的代码,那么编译器会抱怨,“财产必须初始化或抽象”。如何避免重复init内的所有内容?

1 个答案:

答案 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())
}