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のTrailing lambdaについて

0
Last updated at Posted at 2026-07-28

Android アプリ開発始めた瞬間に詰まったのでメモ。

setContent {
    MyApplicationTheme {
        Scaffold { innerPadding ->
            Greeting(
                modifier = Modifier.padding(innerPadding)
            )
        }
    }
}

innerPadding ->ってなんだっけ!?

Trailing lambda

まず以下のような関数があったとする。actionは引数返り値なしの関数型の引数。

fun execute(action: () -> Unit) {
    action()
}

呼び出すときは、

execute(
    action = {
        println("Hello")
    }
)

Kotlinでは関数を呼び出すとき、最後の引数がラムダ式なら()の外へ書ける。

execute {
    println("Hello")
}

引数を持つ関数型の場合は、

fun execute(action: (String) -> Unit) {
    action("Android")
}

呼び出すときは

execute { name ->
    println(name)
}

nameじゃなくて、innerpaddingでもよい。

execute { innerpadding ->
    println(innerpadding)
}

つまり関数ポインタで渡される関数の引数に近いと思う。
executeの引数が二つのときは、

fun execute(message: String, action: (String) -> Unit) {
    action(message)
}
execute("Android") { name ->
    println(name)
}

みたいに書ける。

参考

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?