简体   繁体   中英

kotlin lazy initialized property can not be modified in init block

I have some properties in my class which are initialized lazily. I want them to be immutable which is why I don't use lateinit and I don't want them to be nullable, so I think lazy is the best option here.

in the init block of my class, I want to modify one of the properties but it gives me the compilation error: Variable 'mLstQuestions' must be initialized .
I understand that lazy properties are initialized as soon as they used, so why this is happening? how can I fix this? what is the better approach?

if I create a function Initialize() and modify it in that function. it's perfectly ok and I can call it in the init block.why is that? does this work fine? what is the difference? if doing something like this is forbidden in the init block, shouldn't function call be forbidden too?

This is my code:

class CharacterListView(
    inflater: LayoutInflater,
    parent: ViewGroup
) {
    init {
        mLstQuestions.adapter = mQuestionsListAdapter
        // error : Variable 'mLstQuestions' must be initialized
        // error : Variable 'mQuestionsListAdapter' must be initialized
    }
    
    private val mLstQuestions by lazy { findViewById<RecyclerView>(R.id.char_list) }
    private val mQuestionsListAdapter by lazy { QuestionsListAdapter(getContext(), this) }
    private val mRootView by lazy { inflater.inflate(R.layout.activity_main, parent, false) }
...
}

and this is the code with initialize function:

class CharacterListView(
    inflater: LayoutInflater,
    parent: ViewGroup
) {
    init { initialize() } // no errors!

    private fun initialize() {
        mLstQuestions?.adapter = mQuestionsListAdapter
    }

    private val mLstQuestions by lazy { findViewById<RecyclerView>(R.id.char_list) }
    private val mQuestionsListAdapter by lazy { QuestionsListAdapter(getContext(), this) }
    private val mRootView by lazy { inflater.inflate(R.layout.activity_main, parent, false) }
...
}

Please try to define the init{ } block after the declaration of your variables.

class CharacterListView(
    inflater: LayoutInflater,
    parent: ViewGroup
) { 
    private val mLstQuestions by lazy { findViewById<RecyclerView>(R.id.char_list) }
    private val mQuestionsListAdapter by lazy { QuestionsListAdapter(getContext(), this) }
    private val mRootView by lazy { inflater.inflate(R.layout.activity_main, parent, false) }

init {
        mLstQuestions.adapter = mQuestionsListAdapter
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM