Search code examples
arraysscalavectormappingtemporary

map Range directly to Array


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?


Solution

  • 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.