【问题标题】:Very weird type mismatch in ScalaScala中非常奇怪的类型不匹配
【发布时间】:2015-10-02 23:57:03
【问题描述】:

为什么我在触发 printGenericType(new Box[Master]()) 时会出现错误,而在 new Box[Master]() 上运行 printGenericType(new Box()) 时不会出现任何错误?

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

【问题讨论】:

    标签: scala generics variance


    【解决方案1】:

    你需要定义类型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")
      }
    }
    

    【讨论】:

    • 我认为定义边界 (>:) 可以替代协变声明 -T
    • 我的目标是获得box的泛型类型。
    • 使用 (>:) 你只说T 应该是Tool 的超类型,但它没有说明这种类型的协方差/逆变。您需要明确指定它。
    猜你喜欢
    • 2013-06-10
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多