How to convert List to ListBuffer?
Asked Answered
S

1

30

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:

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.

Siblee answered 21/1, 2013 at 16:32 Comment(3)
Is your concern that toBuffer is not sufficiently performant?Flooring
If I understand correctly, He wants a ListBuffer, not just any Buffer as returned by toBufferKumar
Yeah, I need a ListBuffer. Performance is simply a concern because I'd like to know what's the cost of the conversion (I assume linear), but since this is just part of an initialization step, that might be acceptable.Siblee
P
56

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

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

For scala 2.9.x, you can do:

scala> ListBuffer.empty ++= l
res1: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)
Pule answered 21/1, 2013 at 16:37 Comment(4)
Nice; +1! Just when I was thinking the collections API couldn't be any more magical (from the perspective of 2.8) ...Flooring
++= will reuse the same ListBuffer instead of creating an empty one and then throwing it away again. (Not that creating an empty ListBuffer is particularly expensive.)Carloscarlota
With Scala 2.13: List(1,2,3).to(collection.mutable.ListBuffer) (requires simple parentheses).Ungraceful
@XavierGuihot Thanks . it worked in 2.13. But any idea why in 2.13 it only needs simple paranthesis?Insulate

© 2022 - 2024 — McMap. All rights reserved.