Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type checking has run into a recursive in kotlin

Tags:

android

kotlin

 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);         }     }; 
like image 926
Ankur_009 Avatar asked Aug 01 '17 16:08

Ankur_009


2 Answers

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)     } } 
like image 56
hotkey Avatar answered Oct 14 '22 16:10

hotkey


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()     } } 
like image 27
Peter Avatar answered Oct 14 '22 16:10

Peter