多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# This 表达式 [TOC] 为了表示**当前的接收者对象**我们使用 *this*表达式: * 在[类](http://www.kotlincn.net/docs/reference/classes.html#%E7%BB%A7%E6%89%BF)的成员中,*this*指的是该类的当前对象。 * 在[扩展函数](http://www.kotlincn.net/docs/reference/extensions.html)或者[带有接收者的函数字面值](http://www.kotlincn.net/docs/reference/lambdas.html#%E5%B8%A6%E6%9C%89%E6%8E%A5%E6%94%B6%E8%80%85%E7%9A%84%E5%87%BD%E6%95%B0%E5%AD%97%E9%9D%A2%E5%80%BC)中,*this* 表示在点左侧传递的 _接收者_ 参数。 如果 *this* 没有限定符,它指的是最内层的包含它的作用域。要引用其他作用域中的 *this*,请使用 _标签限定符_: ## 限定的 *this* 要访问来自外部作用域的*this*(一个类或者扩展函数,或者带标签的带有接收者的函数字面值)我们使用`this@label`,其中 `@label` 是一个代指 *this*来源的标签: ```kotlin 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 } } } } ``` 访问来自外部作用域的this(类,扩展函数,带接收者的字面函数),我们使用this@label,其中 @label 是一个代指 this 来源的标签: 示例: ``` fun main(args: Array<String>) { A().B().p() } class A { //隐式标签 @A inner class B { //隐式标签 @B fun p(){ println(this)//输出A$B@279f2327,this代指[B类对象] 666.foo() } fun Int.foo() { //隐式标签 @foo println(this@A)//输出A@2ff4acd0, this代指[A类对象] println(this@B)//输出A$B@279f2327, this代指[B类对象] println(this)//输出666, this代指[foo函数接收者Int类对象] println(this@foo)//输出666, this@foo代指[foo函数接收者Int类对象] val funLit = fun String.() { //this代指[funLit函数接收者String类对象] println(this) //输出lit } "lit".funLit() val funLit2 = { s: String -> //该函数没有接收者,故this代指[foo函数接收者Int类对象] println(this) //输出666 } funLit2("lit2") } } } ```