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】Kotlin 標準ライブラリ:スコープ関数

Posted at

はじめに

Kotlin には、オブジェクトを一時的にスコープに閉じ込めて処理できる スコープ関数 があります。
代表的なのは以下の 5兄弟 です:

  • let
  • run
  • also
  • apply
  • with

それぞれ「戻り値」と「レシーバの参照方法(this / it)」が異なります。


1. let

  • レシーバ参照it
  • 戻り値:ラムダの結果
  • 用途:null安全チェック、値の変換
val name: String? = "Anna"
val length = name?.let {
    println("Name is $it")
    it.length
}
println(length) // 4

2. run

  • レシーバ参照this
  • 戻り値:ラムダの結果
  • 用途:オブジェクトの処理をまとめたい時
val person = Person("Anna", 21)
val description = person.run {
    "Name: $name, Age: $age"
}
println(description) // Name: Anna, Age: 21

3. also

  • レシーバ参照it
  • 戻り値:オブジェクト自体
  • 用途:ログ出力やデバッグなど「副作用」の追加
val list = mutableListOf(1, 2, 3).also {
    println("Before: $it")
    it.add(4)
}
println(list) // [1, 2, 3, 4]

4. apply

  • レシーバ参照this
  • 戻り値:オブジェクト自体
  • 用途:初期化処理に便利
val user = User(1, "Anna").apply {
    println("Setting up user...")
    // プロパティをまとめて設定できる
}

5. with

  • レシーバ参照this
  • 戻り値:ラムダの結果
  • 用途:既存オブジェクトに対する処理をまとめる
val str = "Kotlin"
val result = with(str) {
    println("Length: $length")
    uppercase()
}
println(result) // KOTLIN

6. スコープ関数の比較表

関数 レシーバ参照 戻り値 主な用途
let it ラムダの結果 nullチェック・変換
run this ラムダの結果 オブジェクト処理の集約
also it オブジェクト ログ・副作用
apply this オブジェクト 初期化
with this ラムダの結果 既存オブジェクト処理

まとめ

  • let → 変換やnull安全
  • run → オブジェクト処理をまとめる
  • also → ログ・副作用
  • apply → 初期化処理
  • with → 既存オブジェクトの処理

「戻り値を使いたいか」「オブジェクトを返したいか」で使い分けるのがポイントです。

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?