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】関数型 (Function Type)

Last updated at Posted at 2025-10-03

1. 関数型とは?

Kotlin では、関数そのものを 値(オブジェクト)として扱える ため、変数に代入したり、関数の引数や戻り値に利用できます。
そのときに使われるのが 関数型 (Function Type) です。


2. 関数型の表記

基本形は次のように書きます:

(引数1の型, 引数2の型, ...) -> 戻り値の型

val add: (Int, Int) -> Int = { a, b -> a + b }
println(add(3, 4)) // 7
  • (Int, Int) -> Int が関数型
  • 「2つの Int を受け取り Int を返す関数」を表す

3. 引数なし・戻り値なしの関数型

引数なし

val sayHello: () -> String = { "Hello" }
println(sayHello()) // Hello

戻り値なし(Unit)

val printer: (String) -> Unit = { msg -> println(msg) }
printer("Kotlin!") // Kotlin!

4. 関数型を引数に持つ(高階関数)

関数を引数に取る関数(高階関数)で使われます。

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

val result = operate(3, 4) { a, b -> a * b }
println(result) // 12

op の型が (Int, Int) -> Int であることに注目。


5. 関数型を戻り値にする

関数を返す関数も作れます。

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

val times2 = multiplier(2)
println(times2(5)) // 10

6. 型エイリアス(typealias)

関数型が複雑になる場合、typealias でわかりやすくできます。

typealias IntOperation = (Int, Int) -> Int

val add: IntOperation = { a, b -> a + b }
val multiply: IntOperation = { a, b -> a * b }

println(add(2, 3))      // 5
println(multiply(2, 3)) // 6

7. 関数参照

既存の関数を関数型として渡すこともできます。

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

val f: (Int) -> Int = ::double
println(f(4)) // 8

まとめ

  • 関数型 = (引数の型...) -> 戻り値の型 で表現
  • 変数に代入できる・引数や戻り値にできる
  • 高階関数でよく利用される
  • typealias で読みやすくできる
  • 関数参照 (::関数名) で既存の関数も利用可能

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?