為了表示當前函數的接收者(receiver), 們使用this表達式:
- 在類的成員函數中,this指向這個類的當前對象實例;
- 在擴展函數中,或帶接收者的函數字面值(function literal) 中, this 代表調用函數時, 在點號左側傳遞的接收者參數;
如果this沒有限定符,那么它指向包含當前代碼的最內層范圍.如果想要指向其他范圍內的this,需要使用標簽限定符。
帶限定符的this
為了訪問更外層范圍(比如 類, 或 擴展函數, 或有標簽的 帶接受者的函數字面值)內的 this, 我們使用this@label , 其中的 @label 是一個標簽, 代表我們想要訪問的this所屬的范圍:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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 } } } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/io_field/article/details/53470124