Scala中的路径依赖

时间:2013-01-04 21:38:51

标签: scala path-dependent-type

  trait B {
    type MyInnerType
    def foo: MyInnerType
  }      
  object B1 extends B {
    type MyInnerType = Double
    val foo = 3.0
  }

  trait A {
    type MyInnerType
    val b: B
    def foo(x: b.MyInnerType): MyInnerType
    def bar(y: MyInnerType): Unit
  }
  object A1 extends A {
    type MyInnerType = Int
    val b = B1
    def foo(x: b.MyInnerType) = 1
    def bar(y: MyInnerType) {}
  }
  object A2 extends A {
    type MyInnerType = String
    val b = B1
    def foo(x: b.MyInnerType) = "a"
    def bar(y: MyInnerType) {}
  }

  val as = Seq(A1, A2)
  as foreach { a => a.bar(a.foo(a.b.foo)) }   // wrong, a.foo(a.b.foo) infers to Any

但是,如果a.foo没有参数,那么一切都很完美,a.foo推断a.MyInnerType。如果我施放.asInstanceOf[a.MyInnerType],它也有效。有什么解释吗?

1 个答案:

答案 0 :(得分:1)

我正在运行scala 2.9.1而在REPL上我得到as

scala> val as = Seq(A1, A2)
as: Seq[ScalaObject with A{def foo(x: Double): Any; val b: B1.type; type MyInnerType >: java.lang.String with Int}] = List(A1$@6da13047, A2$@7168bd8b)

然而,当我将其更改为val as:Seq[A] = Seq(A1, A2)时,我得到:

scala> val as:Seq[A] = Seq(A1, A2)
as: Seq[A] = List(A1$@6da13047, A2$@7168bd8b)

scala> as foreach { a => a.bar(a.foo(a.b.foo)) }

有时(始终)scala无法推断类型,因此您必须注释您想要的内容。我经常去REPL找出真正发生的事情。