1

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) {} 
1
  • Assign an object to it before the click listener is called the first time. Commented Nov 24, 2018 at 21:46

1 Answer 1

7

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

1 Comment

Thank you! It was perfect solution! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.