Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic method to convert Array into ListBuffer

I'm looking for a cleaner solution than this:

import scala.collection.mutable.ListBuffer

val y = Array(1,2,3,4)
val z = new ListBuffer[Int]()
y.foreach(elem => z += elem)
like image 866
Hamy Avatar asked Dec 09 '22 06:12

Hamy


2 Answers

Another way is to use to conversion method:

import scala.collection.mutable.ListBuffer

val arr: Array[Int] = Array(1, 2, 3, 4)
val buf: ListBuffer[Int] = arr.to[ListBuffer]

Type annotations on variables are, of course, superfluous, I've added them only for clarity.

to is very versatile, it allows conversion between arbitrary collections (that is, from anything Traversable to anything which has an appropriate CanBuildFrom instance in scope).

like image 121
Vladimir Matveev Avatar answered Dec 27 '22 16:12

Vladimir Matveev


How about:

val z = ListBuffer(y: _ *)

ListBuffer.apply accepts a varargs style sequence of elements. The signature is apply[A](elems: A *): ListBuffer[A] In order to apply a sequence to a function like this, we use the syntax : _ *

like image 38
Michael Zajac Avatar answered Dec 27 '22 14:12

Michael Zajac