【问题标题】:How to resolve expecting class body error in kotlin如何解决 kot​​lin 中的预期类主体错误
【发布时间】:2018-12-17 14:35:48
【问题描述】:

代码:

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)

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

【问题讨论】:

    标签: android kotlin runnable android-handler


    【解决方案1】:

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

    val handler = object : Handler()

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

    val handler = object : Handler(){}

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

    val handler = Handler()

    【讨论】:

      【解决方案2】:

      您可以尝试下一种方法:

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

      【讨论】:

      • 你可以将usingRunnable函数中的代码移动到任何你想要的地方。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      相关资源
      最近更新 更多