为什么在解雇printGenericType(new Box[Master]())
时出现错误,如果我在printGenericType(new Box())
上运行new Box[Master]()
,则不会收到任何错误?
object VarianceExample extends App {
new Box[Master]().printGenericType(new Box()) // ok
new Box().printGenericType(new Box[Master]()) // fail
}
class Box[T >: Tool](implicit m: Manifest[T]) {
def printGenericType(box: Box[T]) = {
println(s"Generic type is [$m] - $box")
}
}
class Master
class Tool extends Master
class Hammer extends Tool
答案 0 :(得分:2)
您需要定义类型T
协变,否则您只能传递构造函数中使用的相同类型。 new Box()
- 为您提供Box[Tool]
(没有任何其他限制),并且您正试图通过Box[Master]
。
在第一个示例中,scalac会自动将new Box()
推断为Box[Master]
,因为它位于Box[Master]
位置。
不确定您想要实现的目标,但要解决具体问题,您需要定义类型Box,如下所示:
class Box[+T >: Tool](implicit m: Manifest[T]) {
def printGenericType[A >: T](box: Box[A]) = {
println(s"Generic type is [$m] - $box")
}
}