val cycleRunnable = Runnable { handler.postDelayed(cycleRunnable,100) }
I am getting error Error:(219, 29) Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly
But its exact java version doesn't have any error
private final Runnable cycleRunnable = new Runnable() { public void run() { handler.postDelayed(cycleRunnable, POST_DELAY); } };
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() } }
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