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】無名関数 (Anonymous Function)

Posted at

1. 無名関数とは?

無名関数 (Anonymous Function) とは、その名の通り 名前を持たない関数 です。
通常の関数と違い fun キーワードを使ってインラインで定義できます。

ラムダ式と似ていますが、無名関数は より「関数らしい書き方」 が可能です。


2. 基本構文

val add = fun(a: Int, b: Int): Int {
    return a + b
}

println(add(3, 4)) // 7
  • fun で定義
  • 引数・戻り値を明示できる
  • 戻り値は return を使う

3. ラムダ式との違い

特徴 ラムダ式 無名関数
宣言方法 { 引数 -> 本体 } fun(引数): 戻り値 { 本体 }
戻り値の型 推論される 明示できる
return の挙動 外側の関数 に適用される場合あり その関数自身 に適用される
可読性 簡潔でシンプル 型を明示したい場合に便利

4. 例:戻り値型を明示

ラムダ式では戻り値の型を明示できませんが、無名関数なら可能です。

val greet = fun(name: String): String {
    return "Hello, $name"
}
println(greet("Anna")) // Hello, Anna

5. 例:高階関数に渡す

無名関数は高階関数の引数としても利用できます。

val numbers = listOf(1, 2, 3, 4)

val doubled = numbers.map(fun(x: Int): Int {
    return x * 2
})

println(doubled) // [2, 4, 6, 8]

6. return の違い(ラムダ vs 無名関数)

ラムダ式

fun testLambda() {
    val list = listOf(1, 2, 3)
    list.forEach {
        if (it == 2) return  // 外側の関数 testLambda を抜ける
        println(it)
    }
    println("End") // 実行されない
}

無名関数

fun testAnonymous() {
    val list = listOf(1, 2, 3)
    list.forEach(fun(it: Int) {
        if (it == 2) return  // 無名関数からだけ抜ける
        println(it)
    })
    println("End") // 実行される
}

無名関数では return が「その関数自身」に作用するため、より直感的に制御できる場合があります。


まとめ

  • 無名関数 = 名前を持たない関数、fun で定義
  • ラムダ式と似ているが、型を明示できる点が強み
  • 高階関数に渡すときや、return の制御を明確にしたいときに便利
  • 実務では ラムダ式が主流 だが、無名関数は状況によって有効

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?