LoginSignup
15
10

More than 5 years have passed since last update.

Kotlin のスコープ関数早見表

Posted at

詳細な説明は Kotlin スコープ関数 用途まとめ - Qiita を参照。

関数 this it 戻り値 定義
let - レシーバ ラムダ式の戻り値 <T, R> T.let(f: (T) -> R): R
with 第一引数の値 - ラムダ式の戻り値 <T, R> with(receiver: T, f: T.() -> R): R
run レシーバ - ラムダ式の戻り値 <T, R> T.run(f: T.() -> R): R
apply レシーバ - レシーバ <T> T.apply(f: T.() -> Unit): T
also - レシーバ レシーバ <T> T.also(block: (T) -> Unit): T

言葉の説明

  • ラムダ式
    • ここでの「ラムダ式」とは、スコープ関数の引数に渡す関数のこと
    • "hoge".let {...}{...} の部分
  • this 列
    • ラムダ式の中で this が指すもの
  • it 列
    • ラムダ式に渡される引数
  • 戻り値列
    • スコープ関数の戻り値が何になるか
  • レシーバ
    • スコープ関数のレシーバ
    • "hoge".let {...} の場合は "hoge" がレシーバ
  • ラムダ式の戻り値
    • ラムダ式が返した値
    • "hoge".let {"fuga"} の場合は "fuga" のこと
  • 第一引数の値 (with)
    • with("hoge") {...}"hoge" のこと
検証コード
test("let") {
    "hoge".let {
        println("this=$this, it=$it")
        "return value"
    }
}
/* 出力結果
=====let=====
this=Scope_function@6eb089e6, it=hoge
returnValue=return value
*/

test("with") {
    with("hoge") {
        println("this=$this")
        "return value"
    }
}
/* 出力結果
=====with=====
this=hoge
returnValue=return value
*/

test("run") {
    "hoge".run {
        println("this=$this")
        "return value"
    }
}
/* 出力結果
=====run=====
this=hoge
returnValue=return value
*/

test("apply") {
    "hoge".apply {
        println("this=$this")
    }
}
/* 出力結果
=====apply=====
this=hoge
returnValue=hoge
*/

test("also") {
    "hoge".also {
        println("this=$this, it=$it")
    }
}
/* 出力結果
=====also=====
this=Scope_function@6eb089e6, it=hoge
returnValue=hoge
*/

fun test(name: String, testCase: () -> Any) {
    println("\n=====$name=====")
    val returnValue = testCase()
    println("returnValue=$returnValue")
}
15
10
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
15
10