为什么@Transient不能与val字段一起使用?

时间:2019-03-25 00:41:47

标签: kotlin

我写了数据类

data class FileHeader(
    val relativePath: String,
    val orderNumber: Long,
    val bodySize: Int
) : Serializable {
@Transient
var headerSize: Int = 0
    get() = relativePath.length + 8
}

它按我的预期工作。

但是为什么我不能在val字段中使用@Transient?

错误是:

此注释不适用于没有后备字段或委托的目标成员属性

是否有任何理由采用这种方式?

2 个答案:

答案 0 :(得分:1)

注释

  

Marks the JVM backing field of the annotated property as transient, meaning that it is not part of the default serialized form of the object.

默认序列化适用于字段,并且不关心getter方法。因此,如果没有后备字段,则无需序列化(也无需在字节码中标记为transient)。在这种情况下,注释将是无用的,因此设计人员选择使其成为错误。

如果您看不到为什么没有后备字段:

  

A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier.

使用var时,默认设置员需要支持字段;当您将其更改为val时,不是。

答案 1 :(得分:0)

试试这个

@get:javax.persistence.Transient
val headerSize
  get() { ... }