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")))
以上輸出Thing of int和Thing of string。我的問題是,如果型別橡皮擦啟動,為什么型別資訊在運行時仍然可用?
uj5u.com熱心網友回復:
這不是型別擦除開始的時候,如果你試試這個:
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")))
你會得到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"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/523365.html
標籤:斯卡拉仿制药类型擦除擦除
