[英]In Scala, how to create a trait for classes with functions using different context bounds
Now I wanna serialize/deserialize Json data, and there are several json libraries to choose. 现在我想序列化/反序列化Json数据,并且有几个json库可供选择。 However, they use different context-bounds for encoding/decoding, which make it hard to define a trait for them.
但是,它们使用不同的上下文边界进行编码/解码,这使得很难为它们定义特征。
trait JsonLib {
// def writes[T](data: T): String
// def reads[T](jsonStr: String): Option[T]
}
object JsonCirce extends JsonLib {
import io.circe.Encoder._
import io.circe.Decoder._
def writes[T: Encoder](data: T): String = ...
def reads[T: Decoder](jsonStr: String): Option[T] =
}
//spray-json
object JsonSpray extends JsonLib {
import spray.json._
def writes[T: JsonWriter](data: T): String = ...
def reads[T: JsonReader](jsonStr: String): Option[T] = ...
}
Is there a way to define the writes/reads in the trait? 有没有一种方法可以定义特征中的写入/读取?
You can generalize the type classes using higher kind types like: 您可以使用更高种类的类型来概括类型类:
import scala.language.higherKinds
import scala.util.Try
import spray.json._
import DefaultJsonProtocol._
trait JsonLib[R[_], W[_]] {
def writes[T: W](data: T): String
def reads[T: R](jsonStr: String): Option[T]
}
//spray-json
object JsonSpray extends JsonLib[JsonReader, JsonWriter] {
override def writes[T: JsonWriter](data: T): String =
data.toJson.compactPrint
override def reads[T: JsonReader](jsonStr: String): Option[T] =
Try(jsonStr.parseJson.convertTo[T]).toOption
}
// Test
JsonSpray.writes(List(1, 2))
JsonSpray.reads[List[Int]]("[1,2]")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.