kotlin小ネタ:Handler#postDelayed()のextension function化

普通に Handler#postDelayed() を利用すると以下のようになり、結構見づらい。

mHandler.postDelayed(
    {
        println("postDelayed()")
    },
    2000)


kotlinでは、関数の最終引数が関数の場合には、ラムダ式を括弧の外側に記述できる。
Higher-Order Functions and Lambdas - Kotlin Programming Language

In Kotlin, there is a convention that if the last parameter to a function is a function, and you're passing a lambda expression as the corresponding argument, you can specify it outside of parentheses


ということで、以下のような extension function を用意する。*1

fun Handler.postDelayed(delayMillis: Long, r: () -> Unit) {
    postDelayed(r, delayMillis)
}


すると、ラムダ式を関数の body のような感じで書ける。

mHandler.postDelayed(2000){
    println("postDelayed()")
}


いい感じ(`・ω・´)

*1:kotlin と android の両方に依存するスコープ用のライブラリ内に配置すると便利。