kotlin this keyword

1. Meaning

  • In the process and properties: this call on behalf of the method and object properties;
  • In the constructor: this represents the object constructor impending return change;
  • . "": Anonymous extension functions extension functions or with the recipient of this recipient on behalf of the left;
  • If this is not a qualifier, this represents the innermost priority recipient, and then click Search outward.

2. Example

fun main() {
    ThisModifier().thisFun()
    ThisModifier().extendsMethod()
}

class ThisModifier {
    val param: Int

    init {
        this.param = 3//在属性里,this代表调用该方法对象(ThisModifier的实例)
    }

    fun thisFun() {
        println(this.param)//在方法里,this代表调用该方法对象(ThisModifier的实例)
    }
}

val extendsMethod = fun ThisModifier.() {
    //在扩展方法(或者带接收者的匿名扩展方法)里this代表接收者
    println("扩展方法里:${this.param}")
}

3.this with the qualifier

fun main() {
    val outer = ThisWithLabel()
    val inner = outer.InnerClass()
    inner.commonFun()
    outer.getOuterInstance()
}

/**
 * 定义一个类
 * 隐式标签@ThisWithLabel
 * 数字编号一样代表对应的输出值一样
 */
class ThisWithLabel {//
    /**
     * 定义一个内部类
     * 隐式标签@InnerClass
     */
    inner class InnerClass {
        /**
         * 定义一个扩展方法
         * 隐式标签@log
         */
        fun String.log() {
            println(this)//① this指代接收者(String字符串)
            println(this@log)//① this@log与上面一样
        }

        /**
         * 定义一个普通方法
         * 普通方法没有隐式标签
         */
        fun commonFun() {
            println(this)//② this指代调用commonFun方法的对象(InnerClass的实例)
            println(this@InnerClass)//② 跟上面一样,this@InnerClass指代调用commonFun方法的对象(InnerClass的实例)
            println(this@ThisWithLabel)//③ this@ThisWithLabel指代外部类对象(ThisWithLabel的实例)
            "扩展方法打印日志".log()//分别打印出:扩展方法打印日志  扩展方法打印日志
        }
    }

    fun getOuterInstance() {
        println(this)//③ this指代调用getOuterInstance方法的对象(ThisWithLabel的实例)
    }
}

Guess you like

Origin www.cnblogs.com/nicolas2019/p/10956986.html