0
  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]。有什么解释吗?

4

1 回答 1

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 看看到底发生了什么。

于 2013-01-04T22:25:31.240 回答