Freewind @ Thoughtworks scala java javascript dart 工具 编程实践 月结 math python english [comments admin] [feed]

(2011-09-13) 如何使用match来检查一个对象的类

广告: 云梯:翻墙vpn (省10元) 土行孙:科研用户翻墙http proxy (有优惠)

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
comments powered by Disqus