The following code creates a temporary Vector:
0.to(15).map(f).toArray
^^^^^^^^
Sequence
^^^^^^^^^^^^^^^
temp Vector
^^^^^^^^^^^^^^^^^^^^^^^
Array
The following code creates a temporary Array:
0.to(15).toArray.map(f)
^^^^^^^^
Sequence
^^^^^^^^^^^^^^^
temp Array
^^^^^^^^^^^^^^^^^^^^^^^
Array
Is there a way to map f over the Sequence and directly get an Array, without producing a temporary?
You can use breakOut
:
val res: Array[Int] = 0.to(15).map(f)(scala.collection.breakOut)
or
0.to(15).map[Int, Array[Int]](f)(scala.collection.breakOut)
or use view
:
0.to(15).view.map(f).to[Array]
See this document for more details on views.
(0 to 15).iterator.map(f).toArray
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