特征类型参数的隐式编码器

时间:2015-04-07 13:46:27

标签: json scala traits argonaut

我想使用argonaut lib将json编码为List[E]类型的字段。

sealed trait Msg[E] {
  val contents: List[E]    

  def send(): Unit = {
    val json = contents.asJson
    println("Sending json: " + json.toString())
  }
}

然后我有一个StringMsg案例类:

case class StringMsg(contents: List[String]) extends Msg[String]

argonaut lib定义JsonIdentity[J]特征:

trait JsonIdentity[J] {
  val j: J

  /**
   * Encode to a JSON value using the given implicit encoder.
   */
  def jencode(implicit e: EncodeJson[J]): Json =
    e(j)
}

当我创建StringMsg的新实例并调用send()方法时,出现以下错误:

StringMsg(List("a","b")).send()
  

无法找到参数e的隐含值:   argonaut.EncodeJson [列表[E]]

1 个答案:

答案 0 :(得分:3)

您的API应该需要来自客户端代码的隐式argonaut.EncodeJson[List[E]]

sealed trait Msg[E] {
  val contents: List[E]
  implicit def encodeJson: argonaut.EncodeJson[List[E]] //to be implemented in subclass   

  def send(): Unit = {
    val json = contents.asJson
    println("Sending json: " + json.toString())
  }
}

//or

abstract class Msg[E](implicit encodeJson: argonaut.EncodeJson[List[E]]) {
  val contents: List[E]

  def send(): Unit = {
    val json = contents.asJson
    println("Sending json: " + json.toString())
  }
}

//or

sealed trait class Msg[E] {
  val contents: List[E]

  def send()(implicit encodeJson: argonaut.EncodeJson[List[E]]): Unit = {
    val json = contents.asJson
    println("Sending json: " + json.toString())
  }
}

客户端代码中的某处:

case class StringMsg(contents: List[String]) extends Msg[String] { 
   implicit val encodeJson = argonaut.StringEncodeJson 
}

//or

import argonaut.StringEncodeJson //or even import argonaut._
case class StringMsg(contents: List[String]) extends Msg[String]() //implicit will be passed here

//or

import argonaut.StringEncodeJson //or even import argonaut._
case class StringMsg(contents: List[String]) extends Msg[String]
val a = StringMsg(Nil)
a.send() //implicit will be passed here