12

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?

4 Answers 4

21

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)
Sign up to request clarification or add additional context in comments.

Comments

19

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.

2 Comments

Could you please explain the "_*" part?
Represents the elements of the Iterable . The underscore represents an individual element and the asterisk signifies: "now take all of them"
4

please try Array(1, 2, 3).toBuffer

Comments

0

For anyone that is now looking for the answer, the answer which has been accepted is deprecated. If you will try to execute it then it will execute it successfully but will give you a warning message. So either you can refer Claire Hou answer or you can use

Array('a','b','c').toIndexedSequence

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.