1.含义

  • 在方法和属性中:this代表调用该方法和属性的对象;
  • 在构造器中:this代表该构造器即将返回的对象;
  • 在扩展函数或者带接收者的匿名扩展函数中:this代表“.”左边的接收者;
  • 如果this没有限定符,this优先代表最内层接收者,并依次向外搜索。

    2.示例

    1. fun main() {
    2. ThisModifier().thisFun()
    3. ThisModifier().extendsMethod()
    4. }
    5. class ThisModifier {
    6. val param: Int
    7. init {
    8. this.param = 3//在属性里,this代表调用该方法对象(ThisModifier的实例)
    9. }
    10. fun thisFun() {
    11. println(this.param)//在方法里,this代表调用该方法对象(ThisModifier的实例)
    12. }
    13. }
    14. val extendsMethod = fun ThisModifier.() {
    15. //在扩展方法(或者带接收者的匿名扩展方法)里this代表接收者
    16. println("扩展方法里:${this.param}")
    17. }

    3.this带限定符

    1. fun main() {
    2. val outer = ThisWithLabel()
    3. val inner = outer.InnerClass()
    4. inner.commonFun()
    5. outer.getOuterInstance()
    6. }
    7. /**
    8. * 定义一个类
    9. * 隐式标签@ThisWithLabel
    10. * 数字编号一样代表对应的输出值一样
    11. */
    12. class ThisWithLabel {//
    13. /**
    14. * 定义一个内部类
    15. * 隐式标签@InnerClass
    16. */
    17. inner class InnerClass {
    18. /**
    19. * 定义一个扩展方法
    20. * 隐式标签@log
    21. */
    22. fun String.log() {
    23. println(this)//① this指代接收者(String字符串)
    24. println(this@log)//① this@log与上面一样
    25. }
    26. /**
    27. * 定义一个普通方法
    28. * 普通方法没有隐式标签
    29. */
    30. fun commonFun() {
    31. println(this)//② this指代调用commonFun方法的对象(InnerClass的实例)
    32. println(this@InnerClass)//② 跟上面一样,this@InnerClass指代调用commonFun方法的对象(InnerClass的实例)
    33. println(this@ThisWithLabel)//③ this@ThisWithLabel指代外部类对象(ThisWithLabel的实例)
    34. "扩展方法打印日志".log()//分别打印出:扩展方法打印日志 扩展方法打印日志
    35. }
    36. }
    37. fun getOuterInstance() {
    38. println(this)//③ this指代调用getOuterInstance方法的对象(ThisWithLabel的实例)
    39. }
    40. }

参考

  1. Kotlin与Java:this关键字 - 简书