1
votes

I have a lot of implicit val for enum to json transformations in my program like that:

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

Note: AuthRoleIndividual extends Enumeration. My approach was to write something like that:

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

But that's not possible. Any ideas?

1
By the way Play JSON already provides Writes and Reads for enumerations - cchantep

1 Answers

1
votes

Firstly, You are misunderstanding the Enumeration value's type, For Enumeration value, the value's type is Value type not Enumeration , so you should bind the implicit for Value type. For Example:

  object State extends Enumeration {
    val A = Value("A")
    val B = Value("B")
  }

  implicit def foo(v: State.Value): String = v.toString + "-Bar"

  val t: String = State.A

Secondly, As the above code, Since the Value type is bind to the object(State.value), you can't create generic implicits for all Enumeration.