Search code examples
scalatype-erasure

Generic method type erasure and pattern matching


This example compiles with warning for type erasure

final case class InvBox[A](b: A)

def maybeeq[A, B](x: InvBox[A], y: InvBox[B]): A = y match {
   case _ : x.type => y.b
}

And this one can't be compiled because two singleton types are different

def maybeeq[A, B](x: InvBox[A], y: InvBox[B]): Unit = {
   implicitly[x.type =:= y.type]
}

Why type erasure effects first example and allowed to prove that "y" is "x.type" on compile time, but makes it impossible to compile code in the second?


Solution

  • It is impossible to match x.type with y.type at compile time, because at compile time A and B is not known. And implicits is a compile time mechanism.