【发布时间】:2016-04-02 04:51:08
【问题描述】:
在这个线程中,我正在为 TraversableLike 编写一个简单的辅助函数:
How to specify a type parameter in calling a function while let the compiler infer the other?
我实现了以下功能:
implicit class TraversableLikeView[A, Repr](self: TraversableLike[A, Repr]) {
def filterByType[B: TypeTag] = new FilterByType[B]
class FilterByType[B: TypeTag] {
def get[That](implicit bf: CanBuildFrom[Repr, B, That]): That = {
val result = self.flatMap{
v =>
val unboxed = Utils.javaUnbox(v)
unboxed match {
case x: B => Some(x)
case _ => None
}
}(bf)
result
}
}
}
使用 TypeTag 是因为 ClassTag.unapply 在处理原始类时遇到了一些问题。但是,当我编译上面的代码时,我收到了以下警告:
Warning:(304, 23) abstract type pattern B is unchecked since it is eliminated by erasure
case x: B => Some(x)
^
这与 TypeTag 声称的做法背道而驰(ClassTag 在这里做得几乎完美)。在这种情况下 TypeTag 失败有什么原因吗?
【问题讨论】:
标签: scala type-erasure