How to resolve "expecting class body" error in kotlin
Asked Answered
C

2

6

The code:

var shouldStopLoop = false

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

handler.post(runnable)

The Expecting a class body error occurs while I am trying to create the val runnable.

Caligula answered 17/12, 2018 at 14:35 Comment(0)
G
3

You can try the following approach:

// 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)
}
Geoid answered 17/12, 2018 at 14:52 Comment(0)
R
9

The error occurs because you are treating Handler as an abstract class in the following statement:

val handler = object : Handler()

This statement needs a class body after it as the error says, like this:

val handler = object : Handler(){}

However, as Handler is not an abstract class, a more appropriate statement will be:

val handler = Handler()

Radii answered 8/5, 2019 at 14:51 Comment(0)
G
3

You can try the following approach:

// 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)
}
Geoid answered 17/12, 2018 at 14:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.