How to convert a Scala Array to ArrayBuffer? - 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?

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)

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.

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

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

Related

Using `Seq::fill` with an existing sequence

I would want to fill a Seq[Seq[Int]] instance with an existing Seq[Int] by using the method fill(n1, n2)(element : A) of the Object Seq, as detailed in the documentation : http://www.scala-lang.org/api/2.12.3/scala/collection/Seq$.html#fillA(elem:=>A):CC[CC[A]]
So I wrote this call :
Seq.fill(width, width)(_random_values.) , with _random_values the existing Seq[Int].
The problem is that the parameter of the second list of fill is an element, not a Seq. So, what could I type to iterate on each _random_values's integers AND to execute the Seq.fill for each current integer ?
Seq.fill is more appropriate to create a Seq base on a static value. For your use case Seq.grouped might be a better fit:
val values: Seq[Int] = List(1, 2, 3, 4)
val result: Seq[Seq[Int]] = values.grouped(2).toSeq
result.foreach(println)
/*
List(1, 2)
List(3, 4)
*/

Scalactic: convert an Iterable to Every

Using scalactic, one can convert an Every to a List like this:
scala> Every(1,2,3).toList
res6: List[Int] = List(1, 2, 3)
How can I perform the reverse operation, though, i.e. try to convert a List or an Iterable to an Every? Is there a built-in method that does this?
Simply:
val everyOpt: Option[Every[Int]] = Every.from(List(1, 2, 3))
If the list is known to be non empty:
val every: Every[Int] = Every.from(List(1, 2, 3)).get

Safely Get Tail of Array

I called tail on an Array, but saw a warning.
scala> val arr = Array(1,2)
arr: Array[Int] = Array(1, 2)
scala> arr tail
warning: there were 1 feature warning(s); re-run with -feature for details
res3: Array[Int] = Array(2)
Scaladocs for Array shows an UnsupportedOperationException [will be thrown]
if the mutable indexed sequence is empty.
Is there a safe, won't throw exception, way to get the tail of an array?
Is there a safe, won't throw exception, way to get the tail of an
array?
You can use drop:
scala> Array(1, 2, 3).drop(1)
res0: Array[Int] = Array(2, 3)
scala> Array[Int]().drop(1)
res1: Array[Int] = Array()
Also note that as mentioned by #TravisBrown in the comment below, drop doesn't differentiate between an empty tail (for collections with one element) and the absence of tail (for empty collections) since in both the cases, drop(1) would return an empty collection.
First of all, the warning doesn't have anything to do with the fact that you're using an unsafe method. If you restart the REPL with -feature you'll see the following:
scala> arr tail
<console>:9: warning: postfix operator tail should be enabled
by making the implicit value language.postfixOps visible...
And a pointer to the documentation for scala.language.postfixOps, which includes the following note:
Postfix operators interact poorly with semicolon inference. Most programmers avoid them for this reason.
This is good advice. Being able to write arr tail instead of arr.tail isn't worth the fuss.
Now about the safety issue. The standard library doesn't provide a tailOption for collections, but you can get the same effect using headOption and map:
scala> val arr = Array(1, 2)
arr: Array[Int] = Array(1, 2)
scala> arr.headOption.map(_ => arr.tail)
res0: Option[Array[Int]] = Some([I#359be9fb)
If this is too verbose or opaque or inefficient for you, you can easily create an implicit class that would add a nicer tailOption to Array (or Seq, or IndexedSeq, etc.).
See #TravisBrown's answer for the reason of your warning.
I would personally use a scala.util.Try rather than his rather clever map on the array's head:
scala> val arr = Array(0, 1, 2)
arr: Array[Int] = Array(0, 1, 2)
scala> scala.util.Try {arr.tail} foreach {t => println(t.mkString(","))}
1,2

Scala convert Iterable or collection.Seq to collection.immutable.Seq

It appears the toSeq method in Scala collections returns a scala.collection.Seq, I could also return a Traversable or Iterable but need to convert this to a scala.collection.immutable.Seq.
Is there an easy way to do this?
Thanks
Richard
Use the to method to convert between arbitrary collection types in Scala 2.10:
scala> Array(1, 2, 3).toSeq
res0: Seq[Int] = WrappedArray(1, 2, 3)
scala> Array(1, 2, 3).to[collection.immutable.Seq]
res1: scala.collection.immutable.Seq[Int] = Vector(1, 2, 3)

Convert an array to a mutable set in Scala?

How does one convert a Scala Array to a mutable.Set?
It's easy to convert to an immutable.Set:
Array(1, 2, 3).toSet
But I can't find an obvious way to convert to a mutable.Set.
scala> val s=scala.collection.mutable.Set()++Array(1,2,3)
s: scala.collection.mutable.Set[Int] = Set(2, 1, 3)
scala> scala.collection.mutable.Set( Array(1,2) :_* )
res2: scala.collection.mutable.Set[Int] = Set(2, 1)
The weird :_* type ascription, forces factory method to see the array as a list of arguments.
Starting Scala 2.10, via factory builders applied with .to(factory):
Array(1, 2, 3).to[collection.mutable.Set]
// collection.mutable.Set[Int] = Set(1, 2, 3)
And starting Scala 2.13:
Array(1, 2, 3).to(collection.mutable.Set)
// collection.mutable.Set[Int] = HashSet(1, 2, 3)