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 int和Thing of string. 我的问题是,如果类型橡皮擦启动,为什么类型信息在运行时仍然可用?
如果您尝试以下操作,则这不是类型擦除开始的时间:
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)