模式匹配为ArrayBuffer和Seq返回不同的结果 [英] pattern match returns a different result for ArrayBuffer and Seq
问题描述
在下面的示例中,有一个函数seqResult
,其模式与Seq
相匹配.另一个接受变量参数的函数调用seqResult
并传入ArrayBuffer
.这导致使用Seq
或ArrayBuffer
调用时模式匹配结果不同.
In the sample below, there is a function seqResult
that pattern matches against a Seq
. Another function that accepts variable arguments calls seqResult
and passes in an ArrayBuffer
. This causes the pattern match result to be different when called with a Seq
or with an ArrayBuffer
.
使用Seq
时,匹配器将击中case head :: rest => ...
;使用ArrayBuffer
时,匹配器将击中case Seq(one, two) => ...
.
With a Seq
the matcher hits case head :: rest => ...
, with an ArrayBuffer
the matcher hits case Seq(one, two) => ...
.
这是一个错误吗?反正有什么方法可以防止这种情况发生?
Is this a bug? Is there anyway to safeguard against this?
如果不是bug,那么匹配一个适用于Seq(a,b)
和ArrayBuffer(a,b)
的1个或多个条目的列表的安全方法是什么?
If it's not a bug, what is a safe way to match a list of 1 or more entries that would work for Seq(a,b)
and ArrayBuffer(a,b)
?
def seqResult(arr:Seq[String]) = arr match {
case Nil => "Nil"
case head :: Nil => "head :: Nil"
case head :: rest => "head :: rest"
case Seq(one, two) => "one, two"
case _ => "other"
}
def varArgResult(args:String*) = seqResult(args)
val ab = varArgResult("one", "two")
val se = seqResult(Seq("one", "two"))
println(ab) //=> "one, two"
println(se) //=> "head :: rest"
推荐答案
::
是List
的提取器对象.由于列表是Seq
的默认实现,因此这是使用Seq(a, b, ...)
时看到的内容.
::
is an extractor object for List
s. Since lists are the default implementation of Seq
, this is what you're seeing when you use Seq(a, b, ...)
.
Seq
的提取器是+:
.
这篇关于模式匹配为ArrayBuffer和Seq返回不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!