Hi! I have a data class with a couple of propertie...
# serialization
h
Hi! I have a data class with a couple of properties that should be marked
@Transient
and they are calculated in the init block, but that doesn't seem to be allowed. It works if I change it to a
lateinit var
but that seems wrong. Is this a bug in kotlinx-serialization or is there a workaround?
c
It looks like the error is that it should have a default value. Source: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#transient-properties
h
That feels like a mistake. I have three values that are computed at initialization and assigned in the init block
c
Yeah I don't mean to offer that as a solution. I would not even consider it as a work-around.
h
I feel like my case would be more common than a transient property you assign with the constructor?
h
Another workaround: store the result of the computation in a private variable and use an initial expression.
h
Yeah, that's what I do now
g
"a transient property you assign with the constructor" so that can't be a constructor parameter.
data class
is coupling property and parameters but here you don't want that. Feels like a simple property (out of the ctor) could be ok but it depends if you need to use those fields in equals/hashcode/toString/copy...
h
Transient in this case means it won't be serialized by kotlinx-serialization
g
If a deserialization is done, Ktx wants to call the constructor but there's no default value for those transients parameters, so it can't construct them.
h
The init block will still be called though
If I remove
@Transient
it works, but then it serializes those properties
a
Suggestion: use getters for computed values:
Copy code
data class Person(val name: String, val age: Int) {
  val isAdult: Boolean get() = age > 18
}
I don’t remember whether
@Transient
is required here
h
A getter does not need Transient, but the computation will be executed every access.
h
Ok, computed values works but I don't want it computed every time
The problem here is that I want to assign a property in my init block and add
@Transient
so it isn't serializaed