scala模式匹配错误

scala模式匹配涉及到泛型时, 如果A在运行时并不存在。这意味着,对于实例来讲,任何参数都将被编译成AnyRef

test("checkList"){
    val a = List(1,2,3,5,6)
    val b = List("1","2")
  
    checkList(a) //List of Ints
    checkList(b) //List of Ints
}
def checkList[A](l: List[A]) = l match {
     case _:List[Int] => println("List of Ints")
    case _:List[String] => println("List of Strings")
    case _ => println("Something else")
}

采用实验性的特性Manifest

def checkList[A](l: List[A])(implicit m: scala.reflect.Manifest[A]) = m.toString match {
    case "Int" => println("List of Ints")
    case "java.lang.String" => println("List of Strings")
    case _ => println("Something else")
}

你可能感兴趣的:(Scala)