kotlin更多語言結構——>This表達式
This表達式
為了表示當前的 接收者 我們使用 this 表達式:
— 在類的成員中,this指的是該類的當前對象。
— 在擴展函數或者帶有接收者的函數字面值中,this 表示在點左側傳遞的 接收者 參數。
如果 this 沒有限定符,它指的是最內層的包含它的作用域。要引用其他作用域中的 this,請使用 標簽限定符
限定的 this
要訪問來自外部作用域的this(一個類 或者擴展函數,或者帶標簽的帶有接收者的函數字面值)我們使 用 this@label ,其中 @label 是一個代指 this 來源的標簽:
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 } } } }
Implicit this
當對 this 調用成員函數時,可以省略 this. 部分。但是如果有一個同名的非成員函數時,請謹慎使用,因為 在某些情況下會調用同名的非成員
fun printLine() { println("Top-level function") }
class A {
fun printLine() { println("Member function") }
fun invokePrintLine(omitThis: Boolean = false) {
if (omitThis) printLine()
else this.printLine()
}
}
A().invokePrintLine() // Member function
A().invokePrintLine(omitThis = true) // Top-level function

浙公網安備 33010602011771號