Search code examples
scalapattern-matchingtype-parameter

Is there workaround against type erasure?


I would like to pattern-match against a generic parameter. I wrote the following example:

new Cls().processA("")   //prints B: C

sealed trait Tr[A, B <: A, C <: A]{
  def getA(str: String): A

  final def processA(str: String): Unit = getA(str) match {
    case b: B => println(s"B: " + b)
    case c: C => println(s"C: " + c)
  }
}

sealed trait A
final case class B() extends A
final case class C() extends A

final class Cls extends Tr[A, B, C] {
  override def getA(str: String): A = C()
}

I understand that B and C parameters are erasured to their lower bound A. Maybe there is some workaround to pattern-match against type parameters?


Solution

  • For this case yes, there is: add import scala.reflect.ClassTag and change the definition of Tr to

    sealed abstract class Tr[A, B <: A : ClassTag, C <: A : ClassTag]
    

    Note that this won't affect is/asInstanceOf.