LoginSignup
8
4

More than 5 years have passed since last update.

Kotlinのrun, let, with, apply, alsoでthis/itが使えるのかどれか

Last updated at Posted at 2018-04-09

Kotlinで使えるrun,let,with,applyのいまいち違いが分からず、どれがthisが使えてitがダメなのか理解できていないので試した。

よく見るアレ

この表が結論なのだが…

戻り値\レシーバ it this
結果 let run / with
自身 also apply

実際に試して覚えることにした。

あと、使用用途もついでに書いた。

run

  • this : 使える
  • it : 使えない
    val string = "a"
    val result = string.run {
        println(this) // => a
        //println(it) // エラー  itは使えない
        1 // 戻り値
    }
    println(result) // => 1

使用用途

nullの場合の制御に使える

    val string: String? = null
    val result = string ?: run {
        "nullだぞ"
    }
    println(result) // => nullだぞ

let

  • this : 使えない
  • it : 使える
    val string = "a"
    val result = string.let {
        //println(this) // エラー  thisは定義されていない
        println(it) // => a
        2 // 戻り値
    }
    println(result) // => 2

使用用途

null時の制御に便利

    val string: String? = "a"
    val result = string?.let {
        "nullじゃないよ"
    }
    println(result) // => nullじゃないよ

with

  • this : 使える
  • it : 使えない
    val string = "a"
    val result = with(string) {
        println(this) // => a
        //println(it) // エラー  itは使えない
        3 // 戻り値
    }
    println(result) // => 3

使用用途

イマイチ分からない、runでいいじゃんって思った

apply

  • this : 使える
  • it : 使えない
  • return使えない!
    //apply
    val string = "a"
    val result = string.apply {
        println(this) // => a
        //println(it) // エラー  itは使えない
        4 // applyブロック内ではreturnは使えない
    }
    println(result) // => a

使用用途

FragmentをnewInstanceしてBundleをセットするパターンによく使う

    companion object {
        // applyの出番!!
        fun newInstance(args: Bundle?): MyFragment =
                MyFragment().apply {
                    args ?: run { Bundle() }
                    arguments = args
                }
    }

also

  • this : 使えない
  • it : 使える
  • return使えない!
    val string = "a"
    val result = string.also {
        // println(this) // エラー  thisは使えない
        println(it) // => a
        5
    }
    println(result) // => a

使用用途

applyと似ているが、ラムダ内外でthisの意味が変わらず。
以下はViewのクリックイベントに使用している。

val button = Button(this).also { button -> 
  button.text = "Click me"
  button.setOnClickListener { 
    startActivity(Intent(this, NextActivity::class.java))
  }
}

8
4
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
8
4