8

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

Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82

2 Answers2

16
if(::apiDisposable.isInitialized)

will solve your problem.

In general,

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

Rahul
  • 4,699
  • 5
  • 26
  • 38
16

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.

Egor
  • 39,695
  • 10
  • 113
  • 130