Kotlin: Init function and variable initialization

Viewed 507

I'm building a component for my app and I started to use init function instead of constructor more often, but now weird thing is happening. If I call function inside init function to initialize list, it throws NullPointerException on that list. Is init function executed before variables are initialized in particular class?

Exception is thrown in removeAllViews.

Code:

init {
        createViews()
    }

    private var viewList = mutableListOf<ViewGroup>()
    private fun createViews(){
        removeAllViews()
        list.forEach { addItem(it) }
        changeViewsState(true)
    }

    private fun removeAllViews(){
        parent.removeAllViews()
        viewList.clear()
    }
1 Answers

From this section fo the offcial documentation: https://kotlinlang.org/docs/classes.html#constructors

During an instance initialization, the initializer blocks are executed in the same order as they appear in the class body, interleaved with the property initializers.

So you should put the variable declaration before the init:

private var viewList = mutableListOf<ViewGroup>()

init {
    createViews()
}
private fun createViews(){
    removeAllViews()
    list.forEach { addItem(it) }
    changeViewsState(true)
}

private fun removeAllViews(){
    parent.removeAllViews()
    viewList.clear()
}
Related