Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

android - Type checking has run into a recursive in 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);
        }
    };
question from:https://stackoverflow.com/questions/45442838/type-checking-has-run-into-a-recursive-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...