Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to check variable with lateinit property is initialized or not

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

like image 295
Kishan Solanki Avatar asked Oct 05 '18 10:10

Kishan Solanki


People also ask

How do you check Lateinit variable is initialized or not Kotlin?

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.

Why Lateinit property has not been initialized?

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.

How do you initialize Lateinit property in Kotlin?

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".

What happens when a field declared as Lateinit is accessed before it is initialized?

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.


2 Answers

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.

like image 165
Egor Avatar answered Oct 23 '22 06:10

Egor


if(::apiDisposable.isInitialized)

will solve your problem.

In general,

::<lateinit variable name>.isInitialized is used to check if it has been initialized.

like image 15
Rahul Sharma Avatar answered Oct 23 '22 07:10

Rahul Sharma