6

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

1 Answer 1

6

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()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.