Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 276
fredoverflow Avatar asked Mar 09 '23 03:03

fredoverflow


2 Answers

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.

like image 117
Ziyang Liu Avatar answered Mar 11 '23 05:03

Ziyang Liu


(0 to 15).iterator.map(f).toArray
like image 45
Dima Avatar answered Mar 11 '23 04:03

Dima