"this" 在 Kotlin 类 中的用途

Purpose of "this" in Kotlin classes

我正在尝试找出 类 中 this 的目的。考虑以下示例:

class TestMe {

    var a: Int = 1
    var b: Int = 2

    fun setValA(value: Int) {
        this.a = value
    }
    fun setValB(value: Int) {
        b = value
    }
}

val testInstance1 = TestMe()
val testInstance2 = TestMe()

testInstance1.setValA(3)
testInstance1.setValB(4)

println("instance 2A: ${testInstance2.a}, instance 2B: ${testInstance2.b}") // 1 2
println("instance 1A: ${testInstance1.a}, instance 1B: ${testInstance1.b}") // 3 4

看来我可以简单地省略 this 值,结果是一样的。我在这里遗漏了什么吗?

非常感谢!

是的,和Java一样,但是如果a也是参数名,你会遇到问题:

fun setValA(a: Int) {
    a = a
}

编译错误:

Val cannot be reassigned

那么你将不得不使用this:

fun setValA(a: Int) {
    this.a = a
}

除了user7294900的回答,this只能在this.<property or method name>中省略,还有很多其他用途:例如this::class,或

fun doSomething(other: OtherClass) {
    other.doSomethingWith(this)
}