Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve expecting class body error in kotlin

The Code:

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 error occurs while I am trying to create the val runnable.

like image 755
curiousgeek Avatar asked Dec 17 '18 14:12

curiousgeek


People also ask

How do you solve expecting top level declaration?

Removing the call to main() fixes the issue.

What is lateinit in Android studio?

The lateinit keyword allows you to avoid initializing a property when an object is constructed. If your property is referenced before being initialized, Kotlin throws an UninitializedPropertyAccessException , so be sure to initialize your property as soon as possible.

How to set an object to null in kotlin?

In kotlin, declaration of variable is different from java as kotlin is null safe language. You have to declare variable nullable. Only then its value can be null. To access nullable values you have to use !! or ? with variable names.


2 Answers

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 more appropriate statement will be:

val handler = Handler()

like image 65
Rahul Tiwari Avatar answered Sep 28 '22 12:09

Rahul Tiwari


You can try next approach:

// 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)
}
like image 39
Sergey Avatar answered Sep 28 '22 13:09

Sergey