Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List to ListBuffer?

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.

like image 862
Dan Avatar asked Jan 21 '13 16:01

Dan


People also ask

How to convert ListBuffer to list in Scala?

If you want to convert ListBuffer into a List , use . toList . I mention this because that particular conversion is performed in constant time. Note, though, that any further use of the ListBuffer will result in its contents being copied first.

What is ListBuffer?

Advertisements. Scala provides a data structure, the ListBuffer, which is more efficient than List while adding/removing elements in a list. It provides methods to prepend, append elements to a list.

Are lists mutable in Scala?

Lists are immutable whereas arrays are mutable in Scala.


1 Answers

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) 
like image 87
Régis Jean-Gilles Avatar answered Sep 20 '22 21:09

Régis Jean-Gilles