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)
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).
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 : _ *
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With