如何解决kotlin中的期望类主体错误

cur*_*eek 5 android runnable kotlin android-handler

编码:

var shouldStopLoop = false

val handler = object : Handler()
val runnable = object: Runnable            //error occurs here
{
    override fun run() {
        getSubsData()
        if(!shouldStopLoop)
        {
            handler.postDelayed(this, 5000)
        }
    }
}

handler.post(runnable)
Run Code Online (Sandbox Code Playgroud)

Expecting a class body尝试创建val runnable.

Rah*_*ari 6

发生错误是因为您Handler在以下语句中将其视为抽象类:

val handler = object : Handler()

正如错误所说,此语句后面需要一个类主体,如下所示:

val handler = object : Handler(){}

但是,由于Handler不是抽象类,因此更合适的语句是:

val handler = Handler()


Ser*_*gey 3

您可以尝试以下方法:

// This function takes a lambda extension function
// on class Runnable as the parameter. It is
// known as lambda with a receiver.
inline fun runnable(crossinline body: Runnable.() -> Unit) = object : Runnable {
    override fun run() = body()
}

fun usingRunnable() {
    val handler = Handler()
    val runnableCode = runnable {
        getSubsData()
        if(!shouldStopLoop)
        {
            handler.postDelayed(this, 5000)
        }
    }
    handler.post(runnableCode)
}
Run Code Online (Sandbox Code Playgroud)