Difference between this.member and this::member in java and kotlin

Viewed 93

What is the main difference in accessing a member reference in kotlin and java

1 Answers

TL;DR

this.member accesses the value of a property/variable when it is executed while this::member gets a reference to the property that can be used later in order to access the property. Property/variable references do not work in Java.

Kotlin

this::member

See this.

this::member gets a property object of the property member. You can use it to get (and set if it is mutable) the value of the member at any point.

If you use this::member, change the value of the member variable and use the reference obtained earlier with this::member, you will get the new value and you can also change the value of the original member using the member reference after you obtained it.

this.member

this.member allows to get (and set if it is mutable) the value of the property at the moment you access this.member.

If you use this.member, change the value of the member varianle and use the value obtained earlier with this::member, you will get the old value and while you can change the obtained value, this will not reflect on the original value.

Example

This example illustrates the difference between this.member and this::member:

class TestClass {
    var member="default value"
    fun showDifference() {
        val obj=TestClass()
        val ref=obj::member
        var value=obj.member
        println(ref.get())//default value
        println(value)//default value
        ref.set("changed by ref")
        println(obj.member)//changed by ref
        println(ref.get())//changed by ref
        println(value)//default value
        obj.member="changed directly"
        println(ref.get())//changed directly
        println(value)//default value
        value="changed by value"
        println(ref.get())//changed directly
        println(value)//changed by value
    }
}

fun main(args: Array<String>) {
    TestClass().showDifference()
}

Java

this::member

In Java, this::member does not work (compiler error), you can only access method references of methods and not variables.

However, you can get a method reference of a getter/setter method and call that method at a later point.

this.member

this.member just accesses the member variable when it is executed.

Related