Skip to content Skip to sidebar Skip to footer

Variable 'runnable' Must Be Initialized

Why does Kotlin complains about this: class MyActivity : Activity { private var handler:Handler = Handler() private var runnable: Runnable = Runnable { /* Do something ver

Solution 1:

Kotlin considers a property uninitialized until the end of its initializer, therefore it cannot be used inside its own initializer, even in lambdas. This semantics is similar to the limitation of local variable usage inside its initializer.

There are several workarounds:

  • Use object expression which lets you reference this of the declared object:

    privatevar runnable: Runnable = object : Runnable {
        overridefunrun() {
            /* Do something very important */
            handler.postDelayed(this, 5000)
        }
    }
    

    This works well only for interfaces as a replacement for lambdas and is not very pretty altogether.

  • Use lateinit var or a delegated property with Delegates.notNull():

    privatelateinitvar runnable: Runnable
    init {
        runnable = Runnable { 
            /* Do something very important */
            handler.postDelayed(runnable, 5000)
        }
    }
    

    The same initializer will work with this declaration:

    privatevar runnable: Runnable by Delegates.notNull()
    
  • Implement and use self-reference for initializers on your own:

    classSelfReference<T>(val initializer: SelfReference<T>.() -> T) {
        val self: T by lazy {
            inner ?: throw IllegalStateException("Do not use `self` until initialized.")
        }
    
        privatevalinner = initializer()
    }
    
    fun<T>selfReference(initializer: SelfReference<T>.() -> T): T {
        return SelfReference(initializer).self
    }
    

    And then you can write something like

    privatevar runnable: Runnable = selfReference { 
        Runnable {
            /* Do something very important */
            handler.postDelayed(self, 5000)
        } 
    }
    

Solution 2:

You can also use

privatevar runnable: Runnable = Runnable {
    /* Do something very important */
    handler.postDelayed(runnable(), 5000)
}

privatefunrunnable() = runnable

Post a Comment for "Variable 'runnable' Must Be Initialized"