Scala 类型橡皮擦

Bos*_*ian 0 generics scala type-erasure erasure

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")))
Run Code Online (Sandbox Code Playgroud)

以上输出Thing of intThing of string. 我的问题是,如果类型橡皮擦启动,为什么类型信息在运行时仍然可用?

Ami*_*Mal 5

如果您尝试以下操作,则这不是类型擦除开始的时间:

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")))
Run Code Online (Sandbox Code Playgroud)

你会得到Thing of int。由于case Thing(value: Int)您基本上是在进行与类型断言的模式匹配,我认为它会是这样的:

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"
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @GaëlJ 当然,但这并不是类型擦除的唯一地方,每当我们对泛型类型进行类型匹配时,类型擦除就会发生,无论是“Thing[Try[Option[List[Int]]]]”还是“Thing” [Int](在我的第一个代码块中)`,因为在运行时,它们都是“事物”,除非我们以某种方式控制泛型类型参数。 (2认同)