Reputation: 19
I have lateinit property in my Kotlin activity, this is simplified version of that:
class CreateNewListOfQuestions : AppCompatActivity() {
lateinit var questionAnswerListOfObjects: ArrayList<QuestionAnswerObject>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_new_list_of_questions)
save.setOnClickListener {
questionAnswerListOfObjects.add(0, QuestionAnswerObject("question", "answer", 1))
}
}
}
The main problem is that when I generate mobile app and press “Save” button app stops working. Logcat shows this error: “lateinit property questionAnswerListOfObjects has not been initialized”
I was trying many ways to initialize it but these ways did not help to me. How should I properly initialize it? I am plining to add to ArrayList many objects of this class:
class QuestionAnswerObject(var question: String, var answer: String, var probability: Int=100) {}
Upvotes: 1
Views: 10658
Reputation: 6602
It depends what you want.
For example if everything you need is using ArrayList<QuestionAnswerObject>
you dont need lateinit
at all:
var questionAnswerListOfObjects = ArrayList<QuestionAnswerObject>()
would be enough
If you want to get from Bundle
or from something else - you must initialize it before using.
Basically lateinit
keyword is used only to say "hey, compiler, I have a variable, it is not initialized yet, but I promise it will be initialized before I use it, so please mark it as not nullable field".
So if you really want to use lateinit
, just init that property earlier, for example add after setContentView
questionAnswerListOfObjects = ArrayList<QuestionAnswerObject>()
Upvotes: 7