I wrote data class
data class FileHeader(
val relativePath: String,
val orderNumber: Long,
val bodySize: Int
) : Serializable {
@Transient
var headerSize: Int = 0
get() = relativePath.length + 8
}
It works as i expect.
But why i can't use @Transient with val field?
The error is:
This annotation is not applicable to target member property without backing field or delegate
Are there any reasons why it implemented in this way?
The annotation
The default serialization works on fields and doesn't care about getter methods. So if there's no backing field, there's nothing to serialize (and nothing to mark as transient in bytecode). The annotation would be useless in this case, so the designers chose to make it an error.
If you don't see why there's no backing field:
With your var, the backing field is needed by the default setter; when you change it to val, it isn't.
Try this
@get:javax.persistence.Transient
val headerSize
get() { ... }