What's the postDelayed() uses in kotlin

0xAliHn picture 0xAliHn · Mar 28, 2018 · Viewed 23.2k times · Source

As I know postDelayed() have two argument runnable and duration delay. What actually does below code in kotlin:

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

Here 1st is two function calling and 2nd is duration delay. Where is runnable? Does this something like lambda for kotlin? Any anyone please explain this?

Answer

s1m0nw1 picture s1m0nw1 · Mar 29, 2018

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().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().postDelayed(r, duration)