对于超类型,Play 框架 implicit val Writes[T] 应该是什么样的?

What should a Play framework implicit val Writes[T] look like for super type?

我应该用什么代替 ??? 以便代码进行类型检查?或者还有什么我应该做的吗?我正在使用 Play 为 类 B、C、D 生成 JSON,它们都扩展了 A(层),但是尝试构建 JSON 的代码只知道它有一个 A , 不是哪个亚型 B、C 或 D。

class Layer

object Layer {
  implicit val layerWrites = new Writes[Layer] {
    def writes(x: Layer) = x match {
      case a: CloudLayer         => ???
      case b: VerticalVisibility => ???
      case c: SkyClear           => ???
    }
  }
}

case class CloudLayer(coverage: String, base: Int) extends Layer
case class VerticalVisibility(height: Int)         extends Layer
case class SkyClear()                              extends Layer

object CloudLayer {
  implicit val cloudLayerWrites = new Writes[CloudLayer] {
    def writes(x: CloudLayer) = Json.obj(
      "layerType" -> "cloudLayer",
      "coverage" -> x.cloudCoverage,
      "base" -> x.base * 100
    )
  }
}

object VerticalVisibility {
  implicit val verticalVisibilityWrites = new Writes[VerticalVisibility] {
    def writes(x: VerticalVisibility) = Json.obj(
      "layerType" -> "verticalVisibility",
      "height" -> x.height * 100
    )
  }
}

object SkyClear {
  implicit val skyClearWrites = new Writes[SkyClear] {
    def writes(x: SkyClear) = Json.obj( "layerType" -> "skyClear" )
  }
}

最简单的解决方案就是从子类的实例中删除 implicit 修饰符,然后显式引用它们:

object Layer {
  implicit val layerWrites = new Writes[Layer] {
    def writes(x: Layer) = x match {
      case a: CloudLayer         => CloudLayer.cloudLayerWrites.writes(a)
      case b: VerticalVisibility =>
        VerticalVisibility.verticalVisibilityWrites.writes(b)
      case c: SkyClear           => SkyClear.skyClearWrites.writes(c)
    }
  }
}

您也可以只废弃单个实例并将它们的内容移动到模式匹配中。

如果您喜欢冒险,Julien Richard-Foy 有一个 pretty neat enhanced version of the Json.writes, etc. macros 适用于密封类型层次结构。