此代码编译:
def wtf(arg: Any) = {
arg match {
case Nil => "Nil was passed to arg"
case List() => "List() was passed to arg"
case _ =>"otherwise"
}
}
但这一个没有:
def wtf(arg: Any) = {
arg match {
case List() => "List() was passed to arg"
case Nil => "Nil was passed to arg"
case _ =>"otherwise"
}
}
线路案例无 => ...被标记为无法访问的代码。为什么在第一种情况下,该行案例列表() => ...是不是标有同样的错误?
实际的答案需要理解一个不幸的实现细节,这花了我很多时间来发现。
1) case List() 调用提取器,在一般情况下不可能进行详尽/不可达性检查,因为提取器调用任意函数。到目前为止一切顺利,我们不能指望能够解决停止问题。
2)早在编译器的“狂野西部”时代,就确定如果“case List()”只是翻译为“case Nil”,则模式匹配可以加快很多(并且不会丢失详尽性检查) “在早期编译阶段,这样就可以避免提取器。情况仍然如此,尽管可以撤消,但显然很多人都被告知“case List() => ”完全没问题,我们不想突然悲观他们的所有代码。所以我必须想出一条路。
通过与其他类一起尝试,您可以根据经验看到 List 具有特权。没有不可达错误。
import scala.collection.immutable.IndexedSeq
val Empty: IndexedSeq[Nothing] = IndexedSeq()
def wtf1(arg: Any) = {
arg match {
case Empty => "Nil was passed to arg"
case IndexedSeq() => "IndexedSeq() was passed to arg"
case _ =>"otherwise"
}
}
def wtf2(arg: Any) = {
arg match {
case IndexedSeq() => "IndexedSeq() was passed to arg"
case Empty => "Nil was passed to arg"
case _ =>"otherwise"
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)