【问题标题】:Why I get No apply function found for scala.Enumeration.Value for enum field?为什么我得到 No apply function found for scala.Enumeration.Value for enum 字段?
【发布时间】:2020-02-04 08:47:18
【问题描述】:

我已经定义了我的枚举字段:

object ContractTypeEnum extends Enumeration {
  type ContractTypeEnum = Value
  val Key1 = Value("key1")
  val Key2 = Value("key2")
}

并在scala中定义了它的映射Postgres

trait  EnumImplicit {
  implicit val ContractTypeEnumMapper = PostgresDriver.createEnumJdbcType("contract_type", ContractTypeEnum)
}

在我的表的案例类中,我将列定义为:

contractType: Option[ContractTypeEnum.ContractTypeEnum]

并创建了它的Implicit Formatter,如下所示:

implicit val contractTypeFormat = new Format[ContractTypeEnum.ContractTypeEnum] {
    def reads(json: JsValue) = JsSuccess(ContractTypeEnum.withName(json.as[String]))
    def writes(myEnum: ContractTypeEnum.ContractTypeEnum) = JsString(myEnum.toString)
  }

我得到的是以下错误:

Error:(61, 92) No apply function found for scala.Enumeration.Value
    implicit val optionFormat: Format[ContractTypeEnum] = Format.optionWithNull(Json.format[ContractTypeEnum])

下面的reader/writer也写了:

object ContractJsonModel {
  implicit val ContractJsonModelFormat = {
    implicit val optionFormat: Format[ContractTypeEnum] = Format.optionWithNull(Json.format[ContractTypeEnum])
    Jsonx.formatCaseClass[ContractJsonModel]
  }
}

什么是错误,我应该如何解决?

【问题讨论】:

    标签: scala enums playframework slick


    【解决方案1】:

    我找到了一个按预期工作的解决方案:

    object ContractTypeEnum extends Enumeration {
      type ContractTypeEnum = Value
      val Key1 = Value("key1")
      val Key2 = Value("key2")
    
      implicit val readsMyEnum = Reads.enumNameReads(ContractTypeEnum)
      implicit val writesMyEnum = Writes.enumNameWrites
    
    }
    

    【讨论】:

      【解决方案2】:

      Json 中有特殊的格式方法用于枚举Json.formatEnum。你可以这样写:

      implicit val optionFormat: Format[Option[ContractTypeEnum]] = Format.optionWithNull(Json.formatEnum(ContractTypeEnum))
      

      另外,您应该将optionFormat 的类型设置为Format[Option[ContractTypeEnum]],而不是Format[ContractTypeEnum]

      或者您可以将format 替换为readswrites 这样

          implicit val optionReads: Reads[Option[ContractTypeEnum]] = Reads.optionWithNull(Reads.enumNameReads(ContractTypeEnum))
          implicit val optionWrites: Writes[Option[ContractTypeEnum]] = Writes.optionWithNull(Writes.enumNameWrites[ContractTypeEnum.type])
      

      【讨论】:

      • formatEnum 在 json 库中不存在。我找不到这个功能。
      • 这很奇怪。也许在您的游戏版本中没有退出该方法。因此,您可以分别定义读取和写入。 Format 只是读写的结合。我编辑了我的答案,并将定义读写的版本放在我的答案末尾
      • 也许可以省略写入,因为 enumeration 存在隐式写入。所以只有reads 就足够了。
      猜你喜欢
      • 2021-10-24
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 2023-01-27
      • 1970-01-01
      相关资源
      最近更新 更多