Reputation: 1249
I have a variable in my fragment class:
private lateinit var dManager: DataManager
And I'm initializing it before the first using here:
override fun onResume() {
super.onResume()
dManager = MyApp.gManager.getDataManager(sp,level,test)
if (dManager.hp< 1) {
...
...
...
}
}
This code works ok for me and most users (99.5%), but sometimes i get crash report
lateinit property dManager has not been initialized
How can this happen? What should I do to prevent it?
Upvotes: 0
Views: 1005
Reputation: 2034
lateinit var makes compiler aware that’s not null
getDataManager(sp,level,test) may return sometimes null so for safe sides your solution would be like as :-
override fun onResume() {
super.onResume()
dManager = MyApp.gManager.getDataManager(sp,level,test)
if (::dbManager.isInitialized && dManager.hp< 1) {
...
...
...
}
}
Upvotes: 1
Reputation: 2326
May be your getDataManager(sp,level,test)
return null
value
OR
As per the document you have to check object with .isInitialized
property.
Returns true if this lateinit property has been assigned a value, and false otherwise.
Check lateinit var is initialized
lateinit var file: File
if (::file.isInitialized) { ... }
Upvotes: 0