Type checking has run into a recursive in kotlin
Kotlin prohibits usage of a variable or a property inside its own initializer.
You can use an object expression to implement Runnable
in the same way as in Java:
val cycleRunnable = object : Runnable { override fun run() { handler.postDelayed(this, 100) }}
Another way to do that is to use some function that will return the Runnable
and to use cycleRunnable
inside the lambda passed to it, e.g.:
val cycleRunnable: Runnable = run { Runnable { println(cycleRunnable) }}
Or see a workaround that allows a variable to be used inside its own initializer through a self reference:
This code will not work out of the box: you need to add the utils from the link above or use the kotlin-fun
library:
val cycleRunnable: Runnable = selfReference { Runnable { handler.postDelayed(self, 100) }}
For anyone seeing this compiler warning, it may be as simple as nesting your code inside a Unit
aka { ... }
Kotlin allows us to assign functions:
fun doSomethingElse() = doSomething()fun doSomething() { }
However, this doesn't work if we're calling the function recursively:
fun recursiveFunction(int: Int) = when (int) { 1 -> { } else -> recursiveFunction() }
The fix is simple:
fun recursiveFunction(int: Int) { when (int) { 1 -> { } else -> recursiveFunction() }}
Show value type explicitly like below:
val cycleRunnable:Runnable = Runnable { handler.postDelayed(cycleRunnable,100)}
This solution solves most of the problems with recursive typechecking problem.
If you are receiving error Variable must be initialized
then you have to declare variable first, and then initialize it with runnable like below:
lateinit var cycleRunnable:Runnable//in constructor or somewhere else:cycleRunnable = Runnable { handler.postDelayed(cycleRunnable,100) }