播放2.3 Scala:明确传递Writer - 需要匹配Option {T] vs T;隐式编写者可以处理两者

时间:2014-09-16 11:29:05

标签: json scala playframework implicit

我有一个case class,其上定义了json.Writes[T]

如果我有一个Option[T],并且在范围内写了implicit,我可以致电Json.toJson(Option[T]);这工作

但是,如果我调用Json.toJson(T)(json.Writes[T]) - 我收到编译错误

类型不匹配;  发现:play.api.libs.json.Writes [models.WorkflowTemplateMilestone] {def writes(o:models.WorkflowTemplateMilestone):play.api.libs.json.JsObject}  必需:play.api.libs.json.Writes [Option [models.WorkflowTemplateMilestone]]  注意:隐含值workflowTemplateMilestoneAPIWrites在此处不适用,因为它位于应用程序点之后且缺少显式结果类型

我是否错误地传递了作家?如果TOption[T]implicit之间,它如何运作?

实际代码如下;如果我错误地确认了这个问题

自定义编剧

implicit val workflowTemplateMilestoneAPIWrites = new Writes[WorkflowTemplateMilestone] {
    def writes(o: WorkflowTemplateMilestone) = Json.obj(
        "id" -> o.id,
        "name" -> o.name,
        "order" -> o.order
      )
  }

WORKS

implicit val workflowTemplateMilestoneAPIWrites = new Writes[List[(WorkflowTemplate, Option[WorkflowTemplateMilestone])]] {
    def writes(l: List[(WorkflowTemplate, Option[WorkflowTemplateMilestone])]) = Json.obj(
      "id" -> l.head._1.id,
      "name" -> l.head._1.name,
      "milestones" ->
        l.map(o =>
          Json.toJson(o._2) **// Writer is picked up through Implict this WORKS**
        )
    )
  }

给予编译错误

implicit val workflowTemplateMilestoneAPIWrites = new Writes[List[(WorkflowTemplate, Option[WorkflowTemplateMilestone])]] {
    def writes(l: List[(WorkflowTemplate, Option[WorkflowTemplateMilestone])]) = Json.obj(
      "id" -> l.head._1.id,
      "name" -> l.head._1.name,
      "milestones" ->
        l.map(o =>
          Json.toJson(o._2)**(WorkflowTemplateMilestone.workflowTemplateMilestoneAPIWrites)** // But if I explicitly pass in the Writer, I get the compile error
        )
    )
  }

谢谢, 布伦特

0 个答案:

没有答案