Почему я получаю Не применять функцию, найденную для scala .Enumeration.Value для поля enum? - PullRequest
0 голосов
/ 04 февраля 2020

Я определил мое поле перечисления:

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

В моем классе case для моей таблицы я определил столбец как:

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

Что такое ошибка и как мне ее исправить?

Ответы [ 2 ]

0 голосов
/ 05 февраля 2020

Я нашел решение, которое работает как положено:

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

}
0 голосов
/ 04 февраля 2020

В перечислениях Json есть специальный метод форматирования Json.formatEnum. Вы можете написать так:

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

Кроме того, вы должны установить тип optionFormat как Format[Option[ContractTypeEnum]], а не Format[ContractTypeEnum]

Или вы можете заменить format на reads и writes вот так

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