map直接映射到Array

fre*_*low 4 arrays mapping scala vector temporary

以下代码创建一个临时Vector:

0.to(15).map(f).toArray
^^^^^^^^
Sequence
^^^^^^^^^^^^^^^
    temp Vector
^^^^^^^^^^^^^^^^^^^^^^^
                  Array
Run Code Online (Sandbox Code Playgroud)

以下代码创建一个临时数组:

0.to(15).toArray.map(f)
^^^^^^^^
Sequence
^^^^^^^^^^^^^^^
     temp Array
^^^^^^^^^^^^^^^^^^^^^^^
                  Array
Run Code Online (Sandbox Code Playgroud)

有没有办法在序列上映射f并直接获取数组,而不产生临时?

Ziy*_*Liu 5

你可以使用breakOut:

val res: Array[Int] = 0.to(15).map(f)(scala.collection.breakOut)
Run Code Online (Sandbox Code Playgroud)

要么

0.to(15).map[Int, Array[Int]](f)(scala.collection.breakOut)
Run Code Online (Sandbox Code Playgroud)

或使用view:

0.to(15).view.map(f).to[Array]
Run Code Online (Sandbox Code Playgroud)

有关视图的更多详细信息,请参阅此文档