this表達式,可以表示當前函數的接收者,在類的成員函數中,this 指向這個類的當前對象實例,在擴展函數中或帶有接收者數字面值,this代表調用函數時,在點號左側傳遞的接收者參數
如果this沒有限定符,那么它指向包含當前代碼的最內層范圍.,如果想指向其他范圍的內的this,需要使用標簽限定符
為了范圍最外層范圍的如類內的this,需要使用this@label,其中@label是一個標簽,代表我們想要訪問的this所屬的范圍
class A { //隱含標簽@A inner class B {//隱含標簽@B fun Int.foo() { val out = this@A //指向A的this val inn = this@B //指向B的this val i = this //指向foo函數的接收者,一個int值 val i1 = this@foo //指向foo函數的接收者,一個int值 var f = lambda@ fun String.() { val d = this//指向f的接收者 } val fun2 = { s: String -> val d = this//foo函數接收者,因為包含當前代碼的lambda 表達式沒有接收者 } } } }