kotlin中this 表达式

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 表达式没有接收者
            }
        }
    }
}

 

posted on 2018-12-20 11:07  LoaderMan  阅读(2519)  评论(0编辑  收藏  举报

导航