Dmitry
Dmitry

Reputation: 5279

Misunderstanding with type checks in Scala

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?

Upvotes: 10

Views: 152

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

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

Upvotes: 5

Related Questions