【问题标题】:Scala: Matching empty sequence against NilScala:将空序列与 Nil 匹配
【发布时间】:2018-07-16 12:00:55
【问题描述】:

为什么会这样:

val x: Seq[Any] = Vector.empty
x match {
 case Nil => 1
 case _ => 2
}

Vector.empty 内部等同于:

private[immutable] val NIL = new Vector[Nothing](0, 0, 0)
override def empty[A]: Vector[A] = NIL

匹配Nil 并返回1Nil 不只是Seq 的特定子类型吗?

如果我使用更通用的Seq.empty,答案将保持不变。这是为什么呢?

【问题讨论】:

  • 我认为这是因为Vector[Nothing]NilAbstractSeq[Nothing] 的实例。 Seq.empty 也有同样的类型。

标签: scala collections pattern-matching hierarchical


【解决方案1】:

通过specification,当x == Nil 匹配时,此模式匹配Seq is defined to be

如果这是一个序列与这个序列具有相同元素的序列以相同的顺序,则为true,否则为false

所以Vector.empty == Nil 是真的。

如果您确实想检查模式匹配中是否有 Nil 对象,请使用以下方法之一:

case _: Nil.type =>
case x if x eq Nil =>

【讨论】:

    猜你喜欢
    • 2014-05-28
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    相关资源
    最近更新 更多