Some(ArrayBuffer("myString", "String")).toList.flatten
First turn the Option[ArrayBuffer[String]] into a List[ArrayBuffer[String]]. Then flatten the List[ArrayBuffer[String]] into a List[String]
Some(ArrayBuffer("myString", "String")).toList.flatten
First turn the Option[ArrayBuffer[String]] into a List[ArrayBuffer[String]]. Then flatten the List[ArrayBuffer[String]] into a List[String]
You can map it further:
Some(ArrayBuffer("myString", "String"))
.map(_.toList)
.get
Instead of get you can use orElse to provide a default value and avoid exception thrown.
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.
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 applyA: ListBuffer[A] In order to apply a sequence to a function like this, we use the syntax : _ *