Issue
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.
Solution
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)
Answered By - Arpit Shukla
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.