scalagenericstype-erasureerasure

Scala type eraser


case class Thing[T](value: T)
def processThing(thing: Thing[_]) = {
  thing match {
    case Thing(value: Int) => "Thing of int"
    case Thing(value: String) => "Thing of string"
    case _ => "Thing of something else"
  }
}

println(processThing(Thing(1)))
println(processThing(Thing("hello")))

Above outputs Thing of int and Thing of string. My question is why the type info is still available in runtime if type eraser kicks in?


Solution

  • This is not when type erasure kicks in, if you try this:

    def processThing(thing: Thing[_]) = {
      thing match {
        case _: Thing[Int] => "Thing of int"
        case _: Thing[String] => "Thing of string"
        case _ => "Thing of something else"
      }
    }
    
    println(processThing(Thing("hello")))
    

    You will get Thing of int. With case Thing(value: Int) you're basically doing a pattern matching with type assertion, I think it would be something like this:

    def processThing(thing: Thing[_]) = {
      thing match {
        case Thing(value) if value.isInstanceOf[Int] => "Thing of int"
        case Thing(value) if value.isInstanceOf[String] => "Thing of string"
        case _ => "Thing of something else"
      }
    }