Home > Software design >  Why can't you change a property value permanently in kotlin?
Why can't you change a property value permanently in kotlin?

Time:06-28

Here's the code:

 class Person(var firstName: String, var lastName: String) {
    var fullName: String =  firstName   lastName
    
    fun fullName() = firstName   lastName

    override fun toString(): String {
        return fullName()
    }
}
fun main(){

    val test = Person("test", "fortest1")
   

    test.lastName = "fortest2"
    
    
    println(test.fullName)
}

The result will only be testfortest1. It looks like you are working with a copy of test once test is created.

CodePudding user response:

This is because fullName is not observing any changes to firstName or lastName. It is initialized when Person is created and stays the same unless explicitly modified. One easy fix for this is to provide a custom getter like this:

val fullName get() =  firstName   lastName

Now it will work as you expect because everytime you read fullName that expression will be evaluated and the result will be returned.

(Also, prefer using vals over vars in data class fields)

  • Related