Kotlin this表達式

爲了表示當前的 接收者 我們使用 this{: .keyword } 表達式:

  • 在類的成員中,this{: .keyword } 指的是該類的當前對象
  • 在擴展函數或者帶接收者的函數字面值中,
    this{: .keyword } 表示在點左側傳遞的 接收者 參數。

如果 this{: .keyword } 沒有限定符,它指的是最內層的包含它的作用域。要引用其他作用域中的 this{: .keyword },請使用 標籤限定符

限定的 this{: .keyword }

要訪問來自外部作用域的this{: .keyword }(一個類 或者擴展函數,
或者帶標籤的帶接收者的函數字面值)我們使用this[@label](https://github.com/label "@label"),其中 [@label](https://github.com/label "@label") 是一個
代指 this{: .keyword } 來源的標籤:

class A { // 隱式標籤 @A
    inner class B { // 隱式標籤 @B
        fun Int.foo() { // 隱式標籤 @foo
            val a = this@A // A 的 this
            val b = this@B // B 的 this

            val c = this // foo() 的接收者,一個 Int
            val c1 = this@foo // foo() 的接收者,一個 Int

            val funLit = lambda@ fun String.() {
                val d = this // funLit 的接收者
            }


            val funLit2 = { s: String ->
                // foo() 的接收者,因爲它包含的 lambda 表達式
                // 沒有任何接收者
                val d1 = this
            }
        }
    }
}