Kotlin's val
attributes, by design are immutable. They are supposed to be fixed and unchangeable after initialization.
However, I accidentally found out that Gson
is able to modify those attributes.
Consider this example:
//Entity class:
class User {
val name: String = ""
val age: Int = 0
}
Since the name
and age
are defined as val
and are initialized to empty string and zero, they must remain the same and never change.
However, this test succeeds:
fun main() {
val json = "{\"name\":\"Mousa\",\"age\":30}"
val user = Gson().fromJson<User>(json, User::class.java)
assert(user.name == "Mousa")
assert(user.age == 30)
print("Success")
}
Using this feature makes the code cleaner. Because those attributes are modified by Gson and cannot be modified by the rest of our code. Otherwise, I need to provide some mutable backing fields for Gson and some immutable attributes for the rest of the code.
I don't know if this is a "Feature" of Gson
or a "Bug". So my question is: can we rely on this, or this behavior might change later?