Scala – 模式匹配“case Nil”为Vector
发布时间:2020-12-16 09:12:33  所属栏目:安全  来源:网络整理 
            导读:在阅读了这个 post之后如何在Vector(或任何实现Seq的任何集合)上使用模式匹配,我测试了这个集合的模式匹配. scala x // Vectorres38: scala.collection.immutable.Vector[Int] = Vector(1,2,3)scala x match { | case y +: ys = println("y: " + "ys: " + ys
                
                
                
            | 
                         
 在阅读了这个 
 post之后如何在Vector(或任何实现Seq的任何集合)上使用模式匹配,我测试了这个集合的模式匹配. 
  
  
  
scala> x // Vector
res38: scala.collection.immutable.Vector[Int] = Vector(1,2,3)
scala> x match {
     |    case y +: ys => println("y: " + "ys: " + ys)
     |    case Nil => println("empty vector")
     | }
<console>:12: error: pattern type is incompatible with expected type;
 found   : scala.collection.immutable.Nil.type
 required: scala.collection.immutable.Vector[Int]
Note: if you intended to match against the class,try `case _: <none>`
                 case Nil => println("empty vector")
                      ^ 
 这是dhg的答案,解释: object +: {
  def unapply[T](s: Seq[T]) =
    s.headOption.map(head => (head,s.tail))
} 
 REPL向我显示 scala> Vector[Int]() == Nil res37: Boolean = true …所以为什么我不能使用这种情况Nil语句的Vector? 解决方法
 比较Vector [Int]()== Nil是可能的,因为您所比较的类型级别没有约束;这允许对集合实现equals,另一方面,通过元素比较来执行元素,而不管集合类型如何: 
  
  
  
        Vector(1,3) == List(1,3) // true! 在模式匹配中,当类型与列表无关(它是一个向量)时,您不能有空列表(Nil)的情况. 你可以这样做: val x = Vector(1,3)
x match {
  case y +: ys => println("head: " + y + "; tail: " + ys)
  case IndexedSeq() => println("empty vector")
} 
 但是我建议在这里使用默认情况,因为如果x没有头元素,那它必须在技术上是空的: x match {
  case y +: ys => println("head: " + y + "; tail: " + ys)
  case _ => println("empty vector")
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
