【发布时间】:2017-02-14 16:12:58
【问题描述】:
我需要通过删除类型的接口传递函数,例如演员的receive 方法。所以我想存储擦除的类型参数并用它来转换参数。
class Store[R,T](val action : R => T)(implicit i : TypeTag[R], o : TypeTag[T]) {
val in : Type = i.tpe
val out : Type = o.tpe
}
object Store {
type Any = Store[_,_]
def apply[R,T](action : R => T)(implicit i : TypeTag[R], o : TypeTag[T]) : Store[R,T] = new Store(action)
}
final case class Box[T](unbox : T)
def getType[T](x : T)(implicit t : TypeTag[T]) : Type = t.tpe
val source = Box("test")
val x = Store[Box[String], Box[Int]](s => Box(s.unbox.length))
val y = Store[Box[Int], Box[Boolean]](i => Box(i.unbox % 3 == 0))
val all : List[Store.Any] = List(x,y)
val a0 = all(0)
val a1 = all(1)
我想像这样链接存储的操作:
val c0 = a0.action(source)
val c1 = a1.action(c0)
明显失败:
error: type mismatch;
found : source.type (with underlying type Box[String])
required: _$1
val c0 = a0.action(source)
^
one error found
我可以在运行时检查所有类型是否匹配:
assert(getType(source) <:< a0.in)
assert(a0.out <:< a1.in)
但是我怎样才能真正将参数转换为适当的类型呢? asInstanceOf 需要编译时类型,而不是运行时反射。还有哪些技巧可用?
【问题讨论】:
标签: scala type-erasure dynamic-cast