Jan Tajovsky
Jan Tajovsky

Reputation: 1211

How to access field value in property get() method

Can I access the value of property in Kotlin get() method?

Consider following:

class MyTest {

    var test: String = "string"
        get() {
            logIt("Property accessed")
            return it
        }

}

The magic variable it does not exists. How am I supposed to access actual property value?

Upvotes: 2

Views: 553

Answers (3)

yole
yole

Reputation: 97178

The magical variable it exists in lambdas. The magical variable used for accessing the property value is called field. See the documentation for more information.

var test: String = "string"
    get() {  
        logIt("Property accessed")
        return field
    }

Upvotes: 5

Avijit Karmakar
Avijit Karmakar

Reputation: 9398

class MyTest {
    var test: String = "string"
        get() {
            logIt("Property accessed")
            return field
        }
}

If you want to get access to the field's value in a getter or setter you can use the reserved word field for it.

Upvotes: 0

Todd
Todd

Reputation: 31710

The field value is in the variable called field:

    var test: String = "string"
    get() {
        logIt("Property accessed")
        return field
    }

Upvotes: 4

Related Questions