when i try to initialize data class it gives me error, kotlin.UninitializedPropertyAccessException: lateinit property article_ has not been initialized. How do i resolve this error and whats way to initialize data class.
model class
data class Article(
val id: Int,
val author: String,
val content: String,
val description: String?)
MainActivity
class TestActivity : AppCompatActivity() {
lateinit var binding: ActivityTestBinding
lateinit var article_: List<Article>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,R.layout.activity_test)
val mainAdapter = MainAdapter(article_)
binding.recView.apply {
this.layoutManager = LinearLayoutManager(this@TestActivity)
this.adapter = mainAdapter
}
}
}
CodePudding user response:
ANSWER:
In onCreate() before this line val mainAdapter = MainAdapter(article_) just initialize the article_ by writing article_ = ArrayList() and the error will be gone.
Cause of Error
You are encountering this error because You need to initialize the lateinit variable article_ before using it and you are not doing it.
If you want to check that either the variable is initialized or not then use ::article_.isInitialized.
Feel free to ask if something is unclear.
CodePudding user response:
Change code like this
binding = DataBindingUtil.setContentView(this,R.layout.activity_test) article_ = ArrayList()
CodePudding user response:
lateinit should only be used when you have a specific reason not to initialize the variable on construction. Here I can see no reason not to make it
var article_: List<Article> = listOf()
or perhaps
val article_: MutableList<Article> = mutableListOf()
and guarantee such error can't happen in the first place.
