I have a variable that is declared like
private lateinit var apiDisposable: Disposable
and then in onPause()
method, I am doing
override fun onPause() {
super.onPause()
if (!apiDisposable.isDisposed)
apiDisposable.dispose()
}
But I get this
kotlin.UninitializedPropertyAccessException: lateinit property apiDisposable has not been initialized
Can anyone tell me how could I check if this variable is initialized or not? Is there any method like isInitialised()
Any help would be appreciated
Along with this modifier, Kotlin provides a couple of methods to check whether this variable is initialized or not. Use "lateInit" with a mutable variable. That means, we need use "var" keyword with "lateInit". "lateInit" is only allowed with non-NULLable data types.
This is because whenever a lateinit property is accessed, Kotlin provides it a null value under the hood to indicate that the property has not been initialized yet.
In order to create a "lateInit" variable, we just need to add the keyword "lateInit" as an access modifier of that variable. Following are a set of conditions that need to be followed in order to use "lateInit" in Kotlin. Use "lateInit" with a mutable variable. That means, we need to use "var" keyword with "lateInit".
Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn't been initialized.
Declare your property as a simple property of a nullable type:
private var apiDisposable: Disposable? = null
Call the method using the safe call notation:
override fun onPause() {
super.onPause()
apiDisposable?.dispose()
}
lateinit
is reserved for variables that are guaranteed to be initialized, if this is not your case - don't use it.
if(::apiDisposable.isInitialized)
will solve your problem.
In general,
::<lateinit variable name>.isInitialized
is used to check if it has been initialized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With