What’s the postDelayed() uses in kotlin

The Handler::postDelay documentation can be found here and shows that the method is defined as follows:

boolean postDelayed (Runnable r, long delayMillis)

In idiomatic Kotlin APIs, we would change the order of both parameters and have the function type (i.e. SAM Runnable) as the last argument so that it could be passed outside the parentheses. But sometimes we just have to deal with it, let’s have a look at your example:

Handler(Looper.getMainLooper()).postDelayed({
            sendMessage(MSG, params.id)
            taskFinished(params, false)
        }, duration)

The first argument wrapped in curly braces is a lambda which becomes the Runnable thanks to SAM Conversion. You could make this more obvious by extracting it to a local variable:

val r = Runnable {
     sendMessage(MSG, params.id)
     taskFinished(params, false)
}
Handler(Looper.getMainLooper()).postDelayed(r, duration)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)