【问题标题】:Why @Transient can't be used with val fields?为什么 @Transient 不能与 val 字段一起使用?
【发布时间】:2019-03-25 00:41:47
【问题描述】:

我写了数据类

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

它按我的预期工作。

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

错误是:

此注解不适用于没有支持字段或委托的目标成员属性

以这种方式实现有什么原因吗?

【问题讨论】:

  • 您使用的是哪个版本的 Kotlin?我用 1.3.21 试过这个,它似乎工作。
  • @AlexanderEgger 正如预期的那样,我在try.kotlinlang.org 上收到错误消息。也许您没有将var 更改为val
  • 版本为 1.3.20

标签: kotlin


【解决方案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 时,它不是。

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 2021-06-14
      • 2012-10-09
      • 2020-03-18
      • 2017-11-21
      相关资源
      最近更新 更多