I have a sealed trait that encapsulates an enum type like below:
sealed trait MyType
object MyType {
case object Type1 extends MyType
case object Type2 extends MyType
}
I will get this as a JSON request and I'm finding it a bit difficult to read the incoming String to a case object. Here is what I have:
implicit val myFormat: Format[MyType] = new Format[MyType] {
override def reads(json: JsValue): JsResult[MyType] = (json \ "type").as[String] match {
case "MyType1" => MyType.Type1
case "MyType2" => MyType.Type2
}
.....
.....
It however fails compilation saying that:
Expected JsResult[MyType] but found MyType.Type1.type
What is wrong with my approach?
Fixed it like this:
implicit val myTypeReads: Reads[MyType] = Reads {
case JsString("MyType1") => JsSuccess(MyType1)
case JsString("MyType2") => JsSuccess(MyType2)
case jsValue => JsError(s"MyType $jsValue is not one of supported [${MyType.values.mkString(",")}]")
}