我有以下涉及类型参数和类型成员嵌套结构:从类型参数和类型成员聚集类型信息
trait B
trait B1 extends B
trait U {
type _B <: B
}
type U1 = U {
type _B = B1
}
class Q[_U <: U] {
override def toString() : String = {
// print out type information on B here...
}
}
def test() {
val q = new Q[U1]()
println(q.toString())
}
这似乎是不可能的我收集,因为这样U1在运行时B上的类型信息被指定。
我错了吗?如果不是的话,是否有一个解决方案,在设置上有微小的变化?
感谢来自Kipton巴罗斯的答案,我想出了以下设置:
trait B
trait B1 extends B
trait B2 extends B
trait U {
type _B <: B
implicit val mfB : Manifest[_B]
}
class U1 extends U {
type _B = B1
val mfB : Manifest[_B] = implicitly
}
class U2 extends U {
type _B = B2
val mfB : Manifest[_B] = implicitly
}
class Q[_U <: U](u : _U) {
override def toString() : String = {
"B: " + u.mfB.erasure.getName()
}
}
def test() {
println(new Q(new U1) toString)
println(new Q(new U2) toString)
}
这种方法唯一的缺点就是需要U.
的实例
谢谢,我更新了我的答案,以澄清你的观点。你有没有想过为什么我的例子中的case(4)会打印'Nothing'?这令我感到惊讶,因为在呼叫站点的类型推断确定类型参数“B”为“B1”,是正确的吗? –