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

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

1.this表達(dá)式

在kotlin中,可用this表達(dá)式表示當(dāng)前接收者(receiver)對(duì)象
    1.在類成員函數(shù)中,this代指該類的當(dāng)前對(duì)象;
    2.在擴(kuò)展函數(shù)(extension function)
        或者帶接收者的字面函數(shù)(function literal with receiver)中,
        this代指該函數(shù)的接收者對(duì)象參數(shù)(receiver parameter);

如果this沒有限定符(qualifiers),代指包含它的最內(nèi)層作用域的對(duì)象;
如果要使用外部作用域的this,就要添加this標(biāo)簽限定符(label qualifiers)

2.this限定符(Qualifier)-this@label

訪問來自外部作用域的this(類,擴(kuò)展函數(shù),帶接收者的字面函數(shù))
我們使用this@label,其中 @label 是一個(gè)代指 this 來源的標(biāo)簽:
fun main(args: Array<String>) {
    A().B().p()
}

class A { //隱式標(biāo)簽 @A
    inner class B { //隱式標(biāo)簽 @B        
        fun p(){
            println(this)//輸出A$B@279f2327,this代指[B類對(duì)象]
            666.foo()
        }
        
        fun Int.foo() { //隱式標(biāo)簽 @foo

            //輸出A@2ff4acd0, this代指[A類對(duì)象]
            println(this@A)

            //輸出A$B@279f2327, this代指[B類對(duì)象]
            println(this@B)

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

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

簡書:http://www.lxweimin.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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容