【发布时间】:2016-06-18 19:57:31
【问题描述】:
我有一个带有隐式 TypeTag 参数的反射函数:
def fromOptionFn[R: TypeTag](self: Int => Option[R]): Wrapper[R] = {
println(TypeTag[R])
...
}
由于未知原因不起作用(请参阅How to make Scala type inference powerful enough to discover generic type parameter?):
> fromOptionFn2(v => Some(" + _))
> typeTag(Any)
我推测它是由 Option[R] 推断 R 引起的,所以我稍微改进一下:
def fromOptionFn[R, Opt <: Option[R]: TypeTag](self: Int => Opt): Wrapper[R] = {
println(typeTag[Opt])
...
}
这次更糟糕,甚至没有编译,错误清楚地推断出scala不够聪明,无法分析类型:
> fromOptionFn2(v => Some(" + _))
Error: inferred type arguments [Nothing,Option[String]] do not conform to method fromOptionFn's type parameter bounds [R,Opt <: Option[R]]
那么我该如何暂时规避这个编译问题呢? (当然我可以在 Lightbend 问题跟踪器上报告它,但它太慢了)
附录:这个问题本身是对How to make Scala type inference powerful enough to discover generic type parameter? 的一种尝试规避,可能无法修复。在我的情况下,我不介意获取类型 R 或 Option[R] 的 TypeTag,无论工作如何。
【问题讨论】:
标签: scala type-erasure scala-compiler