10

I have simple type hierarchy in Scala:

trait A {
    trait A1
}

object B extends A {
    case object B1 extends A1
}

object C extends A {
    case object C1 extends A1
}

And, I'm gonna use these types like that:

def get(): Any = C.C1

get() match {
    case _: B.A1 => println("B")
    case _: C.A1 => println("C")
    case _: A#A1 => println("Any")
}

Surprisingly, I'm getting B printed (I've expected C).

Why compiler treats C.C1 as instance of B.A1?

Dmitry Bespalov
  • 5,179
  • 3
  • 26
  • 33
  • I guess this is a problem of type erasure, try `scalac -Xprint:erasure`, your pattern match get compiled to `A.A1` – Herrington Darkholme Oct 15 '15 at 13:11
  • @Zoltán http://www.scala-lang.org/files/archive/spec/2.11/03-types.html#equivalence – Herrington Darkholme Oct 15 '15 at 13:32
  • @HerringtonDarkholme I don't think these are [compound types](http://www.scala-lang.org/old/node/110), but [path-dependent types](http://stackoverflow.com/questions/5581836/why-does-scala-have-path-dependent-types). In any case, my assumption is wrong. – Zoltán Oct 15 '15 at 14:02

1 Answers1

5

This is a known bug.

Scalac does generate a warning for this using the -unchecked flag:

warning: The outer reference in this type test cannot be checked at run time.
            case _: B.A1 => println("B")
                  ^

So right now, B.A1 and C.A1 appear the same to the compiler in the pattern match, because it doesn't check the outer reference to B or C.

See this related discussion.

And SI-4440

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
  • It definitely looks like a bug in compiler. I thought about it, but decided I'm missing something. I really like Scala, and hope this issue will be fixed in future releases. – Dmitry Bespalov Oct 15 '15 at 17:49
  • Though, I didn't manage to get this warning, while playing with `-unchecked` flag. Tried Scala 2.10.5 and 2.11.7. – Dmitry Bespalov Oct 15 '15 at 18:03
  • I didn't get it in the REPL, but I did if I put the same code in a scala file and compiled with scalac. – Michael Zajac Oct 15 '15 at 18:13
  • Right, I've got that warn with `scalac` 2.11.7. Previously, I've tried to compile with SBT. Well, nice to know: at least compiler warns you about the problem :) – Dmitry Bespalov Oct 15 '15 at 18:32