[英]Implicit encoder for a trait type parameter
I would like to encode to json a field of type List[E]
using argonaut lib. 我想使用argonaut lib将
List[E]
类型的字段编码为json。
sealed trait Msg[E] {
val contents: List[E]
def send(): Unit = {
val json = contents.asJson
println("Sending json: " + json.toString())
}
}
Then I have a StringMsg
case class: 然后我有一个
StringMsg
案例类:
case class StringMsg(contents: List[String]) extends Msg[String]
The argonaut lib defines the JsonIdentity[J]
trait: 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)
}
When I create a new instance of StringMsg
and call the send()
method, I have the following error: 当我创建
StringMsg
的新实例并调用send()
方法时,出现以下错误:
StringMsg(List("a","b")).send()
could not find implicit value for parameter e: argonaut.EncodeJson[List[E]]
找不到参数e的隐式值:argonaut.EncodeJson [List [E]]
Your API should require implicit argonaut.EncodeJson[List[E]]
from client code: 您的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())
}
}
Somewhere in the client-code: 客户端代码中的某处:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.