如何解决 kot​​lin 中的 expecting class body 错误

How to resolve expecting class body error in kotlin

代码:

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)

Expecting a class body 在我尝试创建 val runnable 时发生错误。

您可以尝试下一种方法:

// function takes lambda extension function on class Runnable as the parameter, it is known as lambda with 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)
}

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

val handler = object : Handler()

如错误所述,此语句后需要一个 class 正文,如下所示:

val handler = object : Handler(){}

但是,由于 Handler 不是抽象的 class 更合适的说法是:

val handler = Handler()