scala 如何将 List 转换为 ListBuffer?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14443085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:51:38  来源:igfitidea点击:

How to convert List to ListBuffer?

listscalalistbuffer

提问by Dan

Is there any way to efficiently do this, perhaps through toBuffer or to methods? My real problem is I'm building a List off a parser, as follows:

有没有办法有效地做到这一点,也许通过 toBuffer 或方法?我真正的问题是我正在从解析器构建一个列表,如下所示:

lazy val nodes: Parser[List[Node]] = phrase(( nodeA | nodeB | nodeC).*)

But after building it, I want it to be a buffer instead - I'm just not sure how to build a buffer straight from the parser.

但是在构建它之后,我希望它成为一个缓冲区 - 我只是不确定如何直接从解析器构建一个缓冲区。

回答by Régis Jean-Gilles

toindeed does the trick, and it is pretty trivial to use:

to确实可以解决问题,而且使用起来非常简单:

scala> val l = List(1,2,3)
l: List[Int] = List(1, 2, 3)
scala> l.to[ListBuffer]
res1: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)

Works in scala 2.10.x

适用于 Scala 2.10.x

For scala 2.9.x, you can do:

对于 Scala 2.9.x,您可以执行以下操作:

scala> ListBuffer.empty ++= l
res1: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)