0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Kotlin】既存の関数を実行対象として指定したいなら、ラムダより関数参照を使用すべし

Posted at

定義した関数を即時実行ではなく、変数に格納して任意のタイミングで実行したい場合、ラムダより関数参照の方がパフォーマスが良いらしい。

例えば生成した乱数に応じて処理を切り替える場合なんかだと、

main.kt
fun main() {
    val randNum = (1..10).random()
    println(randNum)
    val exec: ()->Unit = when (randNum % 2) {
        0 -> { { do1() } }
        else -> ::do2
    }
    exec()
}

fun do1() {
    println("do 1")
}
fun do2() {
    println("do 2")
}

既存の関数を{{ do1() }}という風にラムダに包んで渡すとラムダの生成コストがかかる。
一方で::do2とすると関数参照といって、新たな関数を生成せず既存のdo2()のメモリアドレスを渡すだけで済む。

まあラムダは「無名」関数なので、既存の関数をラップするなんてそもそも変な話な気もするけれど。
以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?