【发布时间】:2020-12-28 09:03:54
【问题描述】:
我有一个用于 Tuple 的 json 序列化程序。它首先反映元组并构建一个函数,给定一个元组,它将返回一个 (TypeAdapter, value) 对的列表。 (TypeAdapter 是呈现值的特定类型的东西。)看起来像这样:
def extractTuple(p: Product): (Product)=>List[(TypeAdapter[_], Any)] = {
val reflected = reflectOnTuple(tupleClass) // extract a bunch of reflected metadata
val tupleFieldInfo = reflected.tupleFieldInfo
tupleFieldInfos match {
case 1 =>
(p: Product) =>
List( (getTypeAdapterFor(tupleFieldInfo(0)), p.asInstanceOf[Tuple1[_]]._1) )
case 2 =>
(p: Product) =>
List( (getTypeAdapterFor(tupleFieldInfo(0)), p.asInstanceOf[Tuple1[_]]._1),
(getTypeAdapterFor(tupleFieldInfo(1)), p.asInstanceOf[Tuple1[_]]._2) )
//... and so on to Tuple23
}
}
在 JSON 序列化程序中,我有一个 writeTuple() 函数,如下所示。理论上它应该按原样工作,但是......我在 fieldValue 上遇到编译错误,说它是 Any 类型,而预期的是 ?1.T.
TypeAdapter 看起来像:
trait TypeAdapter[T] {
def write[WIRE](
t: T,
writer: Writer[WIRE],
out: mutable.Builder[WIRE, WIRE]): Unit
}
class JsonWriter() {
def writeTuple[T](t: T, writeFn: (Product) => List[(TypeAdapter[_], Any)], out: mutable.Builder[JSON, JSON]): Unit = {
out += "[".asInstanceOf[JSON]
var first = true
writeFn(t.asInstanceOf[Product]).foreach { case (fieldTA, fieldValue) =>
if (first)
first = false
else
out += ",".asInstanceOf[JSON]
fieldTA.write(fieldValue, this, out) // <<-- this blows up (compile) on fieldValue because it's type Any, not some specific field Type
}
out += "]".asInstanceOf[JSON]
}
}
如何让我的 TypeAdapter 相信该字段是正确的类型?
【问题讨论】:
-
你不会在任何地方使用
extractTuple。
标签: scala generics existential-type