Search code examples
classkotlinthisgetter-setter

Purpose of "this" in Kotlin classes


I'm trying to work out the purpose of this in classes. Consider the following example:

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

It seems that I can simply omit this value and the results will be the same. Is there anything that I'm missing here?

Many thanks!


Solution

  • Yes, same as Java, but you will have a problem if a is the parameter name also:

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

    Compilation error:

    Val cannot be reassigned
    

    Then you will have to use this:

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