天天看點

Kotlin-29.this表達式(this Expression)

官方文檔: http://kotlinlang.org/docs/reference/this-expressions.html

1.this表達式

在kotlin中,可用this表達式表示目前接收者(receiver)對象
    1.在類成員函數中,this代指該類的目前對象;
    2.在擴充函數(extension function)
        或者帶接收者的字面函數(function literal with receiver)中,
        this代指該函數的接收者對象參數(receiver parameter);

如果this沒有限定符(qualifiers),代指包含它的最内層作用域的對象;
如果要使用外部作用域的this,就要添加this标簽限定符(label qualifiers)
           

2.this限定符(Qualifier)[email protected]

通路來自外部作用域的this(類,擴充函數,帶接收者的字面函數)
我們使用[email protected],其中 @label 是一個代指 this 來源的标簽:
fun main(args: Array<String>) {
    A().B().p()
}

class A { //隐式标簽 @A
    inner class B { //隐式标簽 @B        
        fun p(){
            println(this)//輸出[email protected],this代指[B類對象]
            666.foo()
        }

        fun Int.foo() { //隐式标簽 @foo

            //輸出[email protected], this代指[A類對象]
            println([email protected])

            //輸出[email protected], this代指[B類對象]
            println([email protected])

            //輸出666, this代指[foo函數接收者Int類對象]
            println(this)

            //輸出666, [email protected]代指[foo函數接收者Int類對象]
            println([email protected])

            val funLit = fun String.() {
                //this代指[funLit函數接收者String類對象]
                println(this) //輸出lit
            }
            "lit".funLit()

            val funLit2 = { s: String ->
                //該函數沒有接收者,故this代指[foo函數接收者Int類對象]
                println(this) //輸出666
            }
            funLit2("lit2")
        }
    }
}
           

簡書:http://www.jianshu.com/p/8112eea496cf

CSDN部落格: http://blog.csdn.net/qq_32115439/article/details/74276017

GitHub部落格:http://lioil.win/2017/07/03/Kotlin-this.html

Coding部落格:http://c.lioil.win/2017/07/03/Kotlin-this.html