class checkType(cls: AnyRef) {
cls match {
case _:String => println("is a string")
case _:Date => println("is a date")
case _ => println("others")
}
}
但对于泛型集合,无法断定其具体类型
var obj : List[Int] = List(1)
val obj2 = List(1.2)
def typeCheck(obj: AnyRef) = obj match{
case _:Array[Int] => println("Array[int]");
case _ : List[Int] => println("List[Int]")
case _ => println("println other type");
}
typeCheck(obj) // 输出List[Int]
typeCheck(obj2) // 输出List[Int]
因为scala和java一样,在运行时把泛型的类型去掉了。
但数组例外
typeCheck(obj.toArray) // 输出Array[Int]
typeCheck(obj2.toArray) // 输出 println other type