scala模式匹配涉及到泛型时, 如果A在运行时并不存在。这意味着,对于实例来讲,任何参数都将被编译成AnyRef
test("checkList"){
val a
= List(1,2,3,5,6)
val b
= List("1","2")
checkList(a
)
checkList(b
)
}
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")
}
转载请注明原文地址: https://yun.8miu.com/read-21254.html