首页 > 解决方案 > 为什么我得到 No apply function found for scala.Enumeration.Value for enum 字段?

问题描述

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

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])

并且还编写了以下阅读器/编写器:

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

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

标签: scalaenumsplayframeworkslick

解决方案


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

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

}

推荐阅读