this表达式,可以表示当前函数的接收者,在类的成员函数中,this 指向这个类的当前对象实例,在扩展函数中或带有接收者数字面值,this代表调用函数时,在点号左侧传递的接收者参数

如果this没有限定符,那么它指向包含当前代码的最内层范围.,如果想指向其他范围的内的this,需要使用标签限定符

为了范围最外层范围的如类内的this,需要使用this@label,其中@label是一个标签,代表我们想要访问的this所属的范围

class A {  //隐含标签@A
    inner class B {//隐含标签@B
        fun Int.foo() {
            val out = this@A   //指向A的this
            val inn = this@B   //指向B的this
            val i = this       //指向foo函数的接收者,一个int值
            val i1 = this@foo //指向foo函数的接收者,一个int值
            var f = lambda@ fun String.() {
                val d = this//指向f的接收者
            }
            val fun2 = { s: String ->
                val d = this//foo函数接收者,因为包含当前代码的lambda 表达式没有接收者
            }
        }
    }
}

 

相关文章:

  • 2021-09-13
  • 2021-06-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-04-22
  • 2022-12-23
  • 2022-01-31
  • 2021-04-27
  • 2021-08-18
  • 2021-09-20
相关资源
相似解决方案