Shapeless TypeCase 奇怪的行为
Shapeless TypeCase Wierd Behavior
在以下代码片段中:
import shapeless._
val stringList = TypeCase[List[String]]
val intList = TypeCase[List[Int]]
def patternMatch(a: Any): Unit = a match {
case stringList(strs) => println("Got Some Strings: " + strs.map(_.size).sum)
case intList(ints) => println("Got Some Ints: " + ints.sum)
case _ =>
}
val ints: List[Int] = Nil
patternMatch(List("hello", "world"))
patternMatch(List(1, 2, 3))
patternMatch(ints) // This was printing "Got Some Strings:..."
最后一个匹配字符串怎么可能?有什么原因吗?
如果至少有一个值不是 String
,则 TypeCase[List[String]]
不匹配。因为 Nil
- 一个空列表 - 没有这样的值,所以它匹配。
在运行时,您无法区分空字符串列表和空整数列表。它们都是同一个对象 - Nil
,没有任何类型信息
在以下代码片段中:
import shapeless._
val stringList = TypeCase[List[String]]
val intList = TypeCase[List[Int]]
def patternMatch(a: Any): Unit = a match {
case stringList(strs) => println("Got Some Strings: " + strs.map(_.size).sum)
case intList(ints) => println("Got Some Ints: " + ints.sum)
case _ =>
}
val ints: List[Int] = Nil
patternMatch(List("hello", "world"))
patternMatch(List(1, 2, 3))
patternMatch(ints) // This was printing "Got Some Strings:..."
最后一个匹配字符串怎么可能?有什么原因吗?
String
,则 TypeCase[List[String]]
不匹配。因为 Nil
- 一个空列表 - 没有这样的值,所以它匹配。
在运行时,您无法区分空字符串列表和空整数列表。它们都是同一个对象 - Nil
,没有任何类型信息