在 Kotlin 中,this 关键字允许我们引用一个类的实例,该类的函数恰好正在运行。此外,还有其他方式可以使 this 表达式派上用场。
this 可以用来访问类的成员我们可以使用 this 作为属性引用或函数调用的前缀:
class Counter {
var count = 0
fun incrementCount() {
this.count += 2
}
}
使用 this 作为前缀,我们可以引用类的属性。 我们可以使用它来解决具有类似名称的局部变量的歧义。
同样,我们也可以使用 this 调用成员函数。
this 访问类实例我们可以使用独立的 this 来表示对象的一个实例:
class Foo {
var count = 0
fun incrementCount() {
incrementFoo(this)
}
}
private fun incrementFoo(foo: Foo) {
foo.count += 2
}
fun main() {
val foo = Foo()
foo.incrementCount()
println("Final count = ${foo.count}")
}
这里,this 表示类本身的实例。 例如,我们可以将类实例作为参数传递给函数调用。
此外,我们可以使用 this 将实例分配给局部变量。
在 Kotlin 中,二级构造函数(secondary constructors)必须委托给主构造函数。 我们可以使用 this 来委托:
class Car(val id: String, val type: String) {
constructor(id: String): this(id, "unknown")
}
这里,Car 的二级构造函数委托给主构造函数。事实上,我们可以在类的主体中定义任意数量的额外的构造函数。