Violetta
Violetta

Reputation: 603

How to write getters in Kotlin

I know a little java and am currently studying kotlin. I can't quite figure out getters. I have a class and some function.

class Client(val personalInfo: PersonalInfo?){} //class

fun sendMessageToClient(client: Client?) {
     val personalInfo: PersonalInfo? = client?.personalInfo
    //...
}

As far as I understand, getter is called in the code client?.personalInfo. Or is it a class field, since private is not explicitly specified anywhere?

Next, I want to add some logic to getter, but I get an error that such a signature already exists.

class Client(val personalInfo: PersonalInfo?){
    fun getPersonalInfo():PersonalInfo?{
        print(personalInfo)
        return personalInfo
    }
}

If I specify that the field is private, the error disappears class Client(private val personalInfo: PersonalInfo?), but but the code client?.personalInfowill not work

I tried to rewrite the code, but I can't figure out how to specify val and pass it a value from the constructor

class Client(personalInfo: PersonalInfo?) {
    val personalInfo = //??
        get() {
            print("personal info $personalInfo")
            return personalInfo
        }
}

Is it possible to somehow add print to the getter and still use client?.personalInfo?

Upvotes: 2

Views: 344

Answers (1)

João Dias
João Dias

Reputation: 17460

You were almost there. When creating custom getters in kotlin you must use the keyword field when you want the value of the associated property to be used (you can read more about this in re reference documentation at https://kotlinlang.org/docs/properties.html#backing-fields or at https://www.baeldung.com/kotlin/getters-setters#1-accessing-the-backing-field):

Every property we define is backed by a field that can only be accessed within its get() and set() methods using the special field keyword. The field keyword is used to access or modify the property’s value. This allows us to define custom logic within the get() and set() methods.

Having written this you just need to change your code a little bit as follows:

class Client(personalInfo: String?) {
    val personalInfo: String? = personalInfo
        get() {
            print("personal info $field")
            return field
        }
}

Upvotes: 5

Related Questions