2

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

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 库定义了JsonIdentity[J]trait:

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[List[E]]

4

1 回答 1

3

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

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
于 2015-04-07T14:10:07.450 回答