Explain how to achieve type erasure workarounds in Scala.

Instruction: Discuss methods to work around type erasure in Scala, including practical examples.

Context: Assesses the candidate's understanding of type erasure in Scala and their ability to implement workarounds to preserve type information at runtime.

Updated

JVM erasure means many generic type arguments are not available for an ordinary runtime class test. For example, testing whether an arbitrary value is a List[String] cannot generally establish its element type by checking the list's class alone. Some generic metadata can exist separately; this does not make every object carry reified element types.

ClassTag[A] supplies the erased runtime class, which is useful for allocating arrays. It does not recursively validate nested generic arguments. To accept an untrusted list of strings, inspect its elements rather than casting after an erased test:

import scala.reflect.ClassTag

def arrayOf[A: ClassTag](values: List[A]): Array[A] = values.toArray

def checkedStrings(value: Any): Option[List[String]] = value match {
  case xs: List[?] =>
    xs.foldRight(Option(List.empty[String])) { (item, tail) =>
      item match {
        case text: String => tail.map(text :: _)
        case _ => None
      }
    }
  case _ => None
}
@main def erasureExample(): Unit = {
  assert(arrayOf(List(1, 2)).sameElements(Array(1, 2)))
  assert(checkedStrings(List("a", "b")).contains(List("a", "b")))
  assert(checkedStrings(List("a", 2)).isEmpty)
  assert(checkedStrings(List.empty[Int]).contains(Nil))
}

The empty list passes this content rule because it contains no non-string element; the check does not recover the original source-level type argument. Null elements are rejected. A schema decoder or an algebraic data type is often a better boundary for complex data.

Scala 2 TypeTag[T] can retain a representation of the statically supplied type T. Comparing typeOf[T] with another type describes that captured type; it is not a deep inspection of an arbitrary runtime object's contents. Scala 3 does not use the same runtime-reflection API; consider typed designs, codecs, or an appropriate TypeTest for abstract runtime tests. A custom type test must implement a sound check and does not magically recover erased information. TypeTags and ClassTags, Scala 3 TypeTest

Related Questions