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.

3
  • Is your concern that toBuffer is not sufficiently performant?
    – cheeken
    Commented Jan 21, 2013 at 16:36
  • If I understand correctly, He wants a ListBuffer, not just any Buffer as returned by toBuffer Commented Jan 21, 2013 at 16:38
  • 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.
    – Dan
    Commented Jan 21, 2013 at 16:43

1 Answer 1

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)
4
  • Nice; +1! Just when I was thinking the collections API couldn't be any more magical (from the perspective of 2.8) ...
    – cheeken
    Commented Jan 21, 2013 at 16:48
  • ++= 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.)
    – Rex Kerr
    Commented Jan 21, 2013 at 17:37
  • 5
    With Scala 2.13: List(1,2,3).to(collection.mutable.ListBuffer) (requires simple parentheses). Commented Jul 1, 2019 at 20:07
  • @XavierGuihot Thanks . it worked in 2.13. But any idea why in 2.13 it only needs simple paranthesis?
    – A srinivas
    Commented Jul 9, 2022 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.