ZetCode

Kotlin 关键字 this

最后修改于 2025 年 4 月 19 日

Kotlin 的 this 关键字指的是当前对象实例。它用于访问类成员和解决作用域歧义。本教程将通过实际例子深入探讨 this 关键字。

基本定义

Kotlin 中的 this 关键字指的是当前的接收者对象。在类成员中,它指的是当前的类实例。在扩展函数中,它指的是接收者参数。this 有助于区分类属性和局部变量。

访问类成员

this 最常见的用法是在与局部变量命名冲突时访问类成员。它明确地指代当前对象的属性和方法。

ClassMembers.kt
package com.zetcode

class Person(val name: String) {
    fun printName() {
        println("Name is ${this.name}")
    }
}

fun main() {
    val person = Person("John Doe")
    person.printName() // Output: Name is John Doe
}

这里,this.name 指的是类属性 name。虽然在这种情况下不是绝对必要的,但使用 this 可以使代码更明确地访问类成员。

解决作用域歧义

当构造函数参数或函数参数与类属性同名时,this 对于区分它们至关重要。

ScopeResolution.kt
package com.zetcode

class Car(val model: String) {
    var speed: Int = 0
    
    fun accelerate(speed: Int) {
        this.speed = speed // 'this' refers to class property
    }
}

fun main() {
    val car = Car("Tesla Model 3")
    car.accelerate(120)
    println("${car.model} is going ${car.speed} km/h")
}

accelerate 方法中,this.speed 指的是类属性,而单独的 speed 指的是参数。如果没有 this,参数将隐藏类属性。

构造函数委托

在 Kotlin 中,this 用于构造函数委托,允许一个构造函数调用同一类中的另一个构造函数。

ConstructorDelegation.kt
package com.zetcode

class Rectangle {
    var width: Int
    var height: Int
    
    constructor(size: Int) : this(size, size)
    
    constructor(width: Int, height: Int) {
        this.width = width
        this.height = height
    }
}

fun main() {
    val square = Rectangle(10)
    val rect = Rectangle(10, 20)
    
    println("Square: ${square.width}x${square.height}")
    println("Rectangle: ${rect.width}x${rect.height}")
}

第一个构造函数使用 this(size, size) 委托给第二个构造函数。当您想提供默认值或多种初始化对象的方法时,这种模式很常见。

扩展函数

在扩展函数中,this 指的是接收者对象 - 被扩展的对象。它提供了对接收者成员的访问。

ExtensionFunctions.kt
package com.zetcode

fun String.addEnthusiasm(level: Int = 1): String {
    return this + "!".repeat(level)
}

fun main() {
    val greeting = "Hello Kotlin"
    println(greeting.addEnthusiasm(3)) // Output: Hello Kotlin!!!
}

这里,扩展函数内部的 this 指的是调用该函数的 String 对象。该函数根据热情程度为字符串添加感叹号。

Lambda 表达式

在带有接收者的 lambda 表达式中,this 指的是在 lambda 的上下文中指定的接收者对象。这在 DSL 和构建器模式中很常见。

LambdaExpressions.kt
package com.zetcode

class Html {
    fun body() = println("Generating body tag")
    fun div() = println("Generating div tag")
}

fun html(init: Html.() -> Unit): Html {
    val html = Html()
    html.init()
    return html
}

fun main() {
    html {
        this.body()
        div() // 'this' is implicit here
    }
}

在传递给 html 的 lambda 中,this 指的是 Html 实例。在 lambda 内部,您可以使用显式的 this 或隐式地调用 Html 方法。

限定 this

在使用嵌套类时,您可能需要限定 this 来引用外部类实例。Kotlin 提供了针对这种情况的语法。

QualifiedThis.kt
package com.zetcode

class Outer {
    val name = "Outer"
    
    inner class Inner {
        val name = "Inner"
        
        fun printNames() {
            println("Inner name: ${this.name}")
            println("Outer name: ${this@Outer.name}")
        }
    }
}

fun main() {
    val outer = Outer()
    val inner = outer.Inner()
    inner.printNames()
}

这里,this@Outer 指的是从内部类中获取的外部类实例。当内部类和外部类具有同名的成员时,这种限定语法是必要的。

使用 this 的最佳实践

来源

Kotlin this 表达式文档

本教程深入介绍了 Kotlin 的 this 关键字,展示了它的各种用法,包括类成员访问、作用域解析和扩展函数。正确使用 this 可以使您的代码更明确,并防止命名冲突,同时保持清晰度。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有多年的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我撰写了 1400 多篇文章和 8 本电子书。我拥有超过八年的编程教学经验。

列出 所有 Kotlin 教程