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
However, if a.foo does not take parameters, everything works perfectly and a.foo infers to a.MyInnerType. It also works if I cast .asInstanceOf[a.MyInnerType]. Any explanations?
I’m running scala 2.9.1 and on the REPL I get this for
as:However, when I change it to
val as:Seq[A] = Seq(A1, A2)I get:Sometimes (all the time) scala has trouble inferring types, so you have to annotate what you want. I go to the REPL often to find out what’s really going on.