Type Erasure in Scala

Solution 1:

In Scala, generics are erased at runtime, which means that the runtime type of List[Int] and List[Boolean] is actually the same. This is because the JVM as a whole erases generic types. All this is due because the JVM wanted to remain backwards compatible way back when generics were first introduced...

There is a way around this in Scala using a ClassTag, which is an implicit parameter that then can be threaded around with whatever generic you are using.

You can think of : ClassTag as passing the type of the generic as an argument. (It is syntactic sugar for passing an implicit parameter of type ClassTag[T].)

import scala.reflect.ClassTag

class SheetUpdater(s: Sheet) {
  def replace3[T <: Group : ClassTag](g: T): Unit = {
    s.children.head match {
      case (_, _:T) => //!
      case (_, _:Attributes) =>
    }
  }
}

Newer answers of this question have more details.