Skip to content
Advertisement

Convert indefinitely running Runnable from java to kotlin

I have some code like this in java that monitors a certain file:

private Handler mHandler = new Handler();
private final Runnable monitor = new Runnable() {

    public void run() {
        // Do my stuff
        mHandler.postDelayed(monitor, 1000); // 1 second
    }
};

This is my kotlin code:

private val mHandler = Handler()
val monitor: Runnable = Runnable {
    // do my stuff
    mHandler.postDelayed(whatToDoHere, 1000) // 1 second
}

I dont understand what Runnable I should pass into mHandler.postDelayed. What is the right solution? Another interesting thing is that the kotlin to java convertor freezes when I feed this code.

Advertisement

Answer

Lambda-expressions do not have this, but object expressions (anonymous classes) do.

object : Runnable {
    override fun run() {
        handler.postDelayed(this, 1000)
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement