模式匹配为ArrayBuffer和Seq返回不同的结果 [英] pattern match returns a different result for ArrayBuffer and Seq

查看:98
本文介绍了模式匹配为ArrayBuffer和Seq返回不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,有一个函数seqResult,其模式与Seq相匹配.另一个接受变量参数的函数调用seqResult并传入ArrayBuffer.这导致使用SeqArrayBuffer调用时模式匹配结果不同.

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 Lists. Since lists are the default implementation of Seq, this is what you're seeing when you use Seq(a, b, ...).

Seq的提取器是+:.

这篇关于模式匹配为ArrayBuffer和Seq返回不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆