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】高階関数 (Higher-Order Function)

Last updated at Posted at 2025-10-03

1. 高階関数とは?

高階関数 (Higher-Order Function) とは:

  • 関数を引数として受け取る関数
  • 関数を戻り値として返す関数

のことを指します。

Kotlin は関数を「第一級オブジェクト」として扱えるため、高階関数を自然に書けます。


2. 基本例:関数を引数に渡す

fun operate(x: Int, y: Int, op: (Int, Int) -> Int): Int {
    return op(x, y)
}

fun main() {
    val sum = operate(3, 4) { a, b -> a + b }
    val product = operate(3, 4) { a, b -> a * b }
    println(sum)     // 7
    println(product) // 12
}
  • op(Int, Int) -> Int という 関数型
  • operate にラムダ式を渡して処理を切り替えられる

3. 関数を戻り値として返す

fun multiplier(factor: Int): (Int) -> Int {
    return { number -> number * factor }
}

fun main() {
    val times2 = multiplier(2)
    println(times2(5)) // 10
}

multiplier(2) は「2倍する関数」を返している。


4. 関数参照と高階関数

既存の関数を 関数参照 (::) で渡せます。

fun double(x: Int): Int = x * 2

val numbers = listOf(1, 2, 3)
val doubled = numbers.map(::double)
println(doubled) // [2, 4, 6]

5. 標準ライブラリの高階関数

Kotlin のコレクション操作は高階関数の代表例です。

map(変換)

val doubled = listOf(1, 2, 3).map { it * 2 }
println(doubled) // [2, 4, 6]

filter(フィルタリング)

val evens = listOf(1, 2, 3, 4, 5).filter { it % 2 == 0 }
println(evens) // [2, 4]

reduce(畳み込み)

val sum = listOf(1, 2, 3, 4).reduce { acc, n -> acc + n }
println(sum) // 10

fold(初期値あり畳み込み)

val sum = listOf(1, 2, 3, 4).fold(0) { acc, n -> acc + n }
println(sum) // 10

6. インライン関数と高階関数

高階関数は関数オブジェクトを生成するため、オーバーヘッドが発生することがあります。
パフォーマンス改善のために inline を使うとよい場合があります。

inline fun repeatAction(times: Int, action: () -> Unit) {
    for (i in 1..times) action()
}

repeatAction(3) { println("Hello") }

まとめ

  • 高階関数 = 関数を引数や戻り値として扱う関数
  • Kotlin では関数型 (A, B) -> C を自然に利用可能
  • map, filter, reduce, fold などの標準関数で活用されている
  • 関数参照 (::) で既存関数を渡せる
  • inline を使えばオーバーヘッドを削減可能

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?