作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
不确定这是一个错误,但以下演示在最终情况下失败:
import spray.json._
import DefaultJsonProtocol._
object SprayTest {
1.toJson
"".toJson
(Left(1): Either[Int, String]).toJson
(Right(""): Either[Int, String]).toJson
Seq(1).toJson
Seq("").toJson
Seq(Left(1), Right("")).toJson
Seq(Left(1), Right("")).toJson(seqFormat(eitherFormat(IntJsonFormat, StringJsonFormat)))
}
Seq
的格式组成和
Either
失败,即使我尝试用勺子喂它。
[error] SprayTest.scala:11: Cannot find JsonWriter or JsonFormat type class for Seq[Product with Serializable with scala.util.Either[Int,String]]
[error] Seq(Left(1), Right("")).toJson
[error] ^
[error] SprayTest.scala:12: type mismatch;
[error] found : spray.json.DefaultJsonProtocol.JF[Either[Int,String]]
[error] (which expands to) spray.json.JsonFormat[Either[Int,String]]
[error] required: spray.json.JsonFormat[Product with Serializable with scala.util.Either[Int,String]]
[error] Note: Either[Int,String] >: Product with Serializable with scala.util.Either[Int,String] (and spray.json.DefaultJsonProtocol.JF[Either[Int,String]] <: spray.json.JsonFormat[Either[Int,String]]), but trait JsonFormat is invariant in type T.
[error] You may wish to define T as -T instead. (SLS 4.5)
[error] Seq(Left(1), Right("")).toJson(seqFormat(eitherFormat(IntJsonFormat, StringJsonFormat)))
最佳答案
这是关于 Either
最烦人的事情之一——Left
和 Right
构造函数都扩展 Product
和 Serializable
,但是 Either
本身没有,这会导致可怕的推断类型:
scala> Seq(Left(1), Right(""))
res0: Seq[Product with Serializable with scala.util.Either[Int,String]] = List(Left(1), Right())
JsonFormat
它的类型参数是不变的,事实上你有一个
A
的实例。并不意味着您有
Product with Serializable with A
的实例.特别是在您的情况下,实际上有一个
Either[Int, String]
的实例,但推断类型中的额外垃圾意味着编译器无法找到它。
Right
,也会发生类似的情况。在序列中:
scala> Seq(Left(1), Left(2)).toJson
<console>:18: error: Cannot find JsonWriter or JsonFormat type class for Seq[scala.util.Left[Int,Nothing]]
Seq(Left(1), Left(2)).toJson
^
scala> val xs: Seq[Either[Int, String]] = Seq(Left(1), Right(""))
xs: Seq[Either[Int,String]] = List(Left(1), Right())
scala> xs.toJson
res1: spray.json.JsValue = [1,""]
Either
来自显式返回
Either
的方法的值而不是使用
Left
和
Right
直接导致这个问题的方式。
Product with Serializable
当您定义自己的 ADT 时。如果标准库设计者遵循了这个建议,我们都会过得更好。
关于json - 喷雾 json 对双子的 Seq 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378223/
我是一名优秀的程序员,十分优秀!