Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Scala Array to ArrayBuffer?

Tags:

scala

I see that a Scala Array can be easily converted to List, Seq etc, using the s.toList or s.toSeq. Now, I would like to convert an array to a bufferarray. How would I do it?

like image 514
zell Avatar asked Feb 04 '18 19:02

zell


2 Answers

There's a generic method to that can convert between arbitrary collection types.

Array(1, 2, 3).to[ArrayBuffer]

Or from Scala 2.13 onwards:

Array(1, 2, 3).to(ArrayBuffer)
like image 160
Jasper-M Avatar answered Oct 15 '22 12:10

Jasper-M


Use Iterable: _*:

val arr = Array(1,2,3)
arr: Array[Int] = Array(1, 2, 3)

val buf = collection.mutable.ArrayBuffer(arr: _*)
buf: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)

The _* means to unpack the Iterable elements. So arr: _* unpacks the elements of arr into a variable length list - which is an acceptable parameter list for `ArrayBuffer.

like image 42
WestCoastProjects Avatar answered Oct 15 '22 13:10

WestCoastProjects