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

はじめに

Kotlin では「すべてが関数」と言えるほど関数の扱いが強力です。
この記事では以下を整理します:

  • トップレベル関数
  • デフォルト引数と名前付き引数
  • 可変引数
  • 式形式関数
  • インライン関数
  • ローカル関数

1. 関数の基本

Kotlinの関数は fun キーワードで定義します。

fun greet() {
    println("Hello, Kotlin!")
}

fun main() {
    greet() // 呼び出し
}

戻り値を返す場合:

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

2. トップレベル関数

Kotlinでは クラスの外 に関数を定義できます。
Javaと違い、ユーティリティ関数をクラスに入れる必要がありません。

fun square(x: Int): Int = x * x

3. デフォルト引数

引数にはデフォルト値を指定できます。

fun greet(name: String, message: String = "Hello") {
    println("$message, $name!")
}

greet("Anna")                 // Hello, Anna!
greet("Anna", "Good morning") // Good morning, Anna!

4. 名前付き引数

引数の名前を指定して呼び出せます。

fun displayUser(name: String, age: Int, country: String) {
    println("Name: $name, Age: $age, Country: $country")
}

displayUser(age = 21, name = "Anna", country = "Japan")

5. 可変引数(vararg)

複数の引数をまとめて受け取れます。

fun sum(vararg numbers: Int): Int {
    return numbers.sum()
}

println(sum(1, 2, 3, 4)) // 10

6. 式形式関数

1行で書ける関数は「式形式」で書けます。

fun square(x: Int) = x * x

7. 高階関数とラムダ式

関数を引数や戻り値として扱うことができます。

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) // 7

8. インライン関数

高階関数のオーバーヘッドを避けるために inline を付けることができます。

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

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

9. ローカル関数

関数の中に関数を定義できます。

fun validate(name: String, age: Int): Boolean {
    fun isNameValid(name: String) = name.isNotEmpty()
    fun isAgeValid(age: Int) = age in 0..120

    return isNameValid(name) && isAgeValid(age)
}

まとめ

  • fun で関数を定義
  • トップレベル関数でクラス外にも定義可能
  • デフォルト引数 & 名前付き引数で呼び出しが柔軟
  • vararg で可変引数を扱える
  • 式形式関数で1行に簡潔に書ける
  • 高階関数・ラムダ式で関数を渡せる
  • 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?