Reputation: 354
I'm initializing response in init block but is throws exception :/ why ?
lateinit var response: MutableLiveData<List<AccessListItem?>>
init {
response.value.apply { emptyList<AccessListItem>() }
}
Exception:
kotlin.UninitializedPropertyAccessException: lateinit property response has not been initialized
Upvotes: 3
Views: 2717
Reputation: 1711
what happening is you are setting the value to the field without actually initializing live data
set
init {
response.value.apply { emptyList<AccessListItem>() }
}
to
init {
response = MutableLiveData()
response.value.apply { emptyList<AccessListItem>() }
}
Upvotes: 0
Reputation: 37799
You're not initializing response
in the init
block (you would need response = something
). You're actually not even initializing response.value
.
What you're actually doing is accessing response.value
, which requires accessing response
, which fails because response
is never initialized.
You need to either initialize response
in the init
block or at the property declaration. Most likely with the MutableLiveData()
constructor, or any other way to get the live data.
For instance, you can initialize the property this way:
val response = MutableLiveData<List<AccessListItem?>>()
Note that you don't need lateinit
nor var
anymore, just a simple val
, because you will not need to change response
(the live data) itself but only its value.
In order to put some value in it, you then need to set response.value
. You can do that with response.value = emptyList()
. Now this piece of code can be put in an init
block like you tried to do:
val response = MutableLiveData<List<AccessListItem?>>()
init {
response.value = emptyList()
}
But you can also use the scope function apply to directly perform this operation when initializing the response
property:
val response = MutableLiveData<List<AccessListItem?>>().apply {
value = emptyList()
}
Upvotes: 3