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
.
Removing the call to main() fixes the issue.
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.
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.
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()
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With