ceran
ceran

Reputation: 1412

Play Writes with generic type parameters

I have a trait Processor that looks like this:

trait Processor[A] {
  def process(in: Seq[Byte]): Result[A]
}

trait Result[A]{
  val ok: Boolean
  val errorMessage: Option[String]
  val data: Option[A]
}

A concrete implementation:

class StringProc extends Processor[String] {
  def process(in: Seq[Byte]): StrResult
}

case class StrResult(...) extends Result[String]
object StrResult {
  implicit val writes = Json.writes[StrResult]
}

When using a StringProc instance as type Processor[String], the return type of process unsurprisingly is Result[String], not StrResult. Unfortunately, the Writes[StrResult] seems to be useless in this case:

No Json serializer found for type Result[String]

How could I handle this situation?

Upvotes: 3

Views: 1605

Answers (1)

cchantep
cchantep

Reputation: 9168

You can try

object Result {
  implicit def resWrites[T](implicit nested: Writes[T]): Writes[Result[T]] = OWrites[Result[T]] { res =>
    Json.obj("ok" -> res.ok, "errorMessage" -> res.errorMessage,
      "data" -> nested.writes(res.data))
  }
}

Upvotes: 6

Related Questions