将 Range 直接映射到 Array
map Range directly to Array
以下代码创建一个临时 Vector:
0.to(15).map(f).toArray
^^^^^^^^
Sequence
^^^^^^^^^^^^^^^
temp Vector
^^^^^^^^^^^^^^^^^^^^^^^
Array
以下代码创建一个临时数组:
0.to(15).toArray.map(f)
^^^^^^^^
Sequence
^^^^^^^^^^^^^^^
temp Array
^^^^^^^^^^^^^^^^^^^^^^^
Array
有没有办法将 f 映射到 Sequence 上并直接得到一个 Array,而不产生一个临时的?
(0 to 15).iterator.map(f).toArray
您可以使用 breakOut
:
val res: Array[Int] = 0.to(15).map(f)(scala.collection.breakOut)
或
0.to(15).map[Int, Array[Int]](f)(scala.collection.breakOut)
或使用view
:
0.to(15).view.map(f).to[Array]
有关视图的更多详细信息,请参阅 this document。
如果您了解如何构建初始 Range
,您也可以使用 Array.range(start, end)
from the Array
companion object 直接创建 Range
作为 Array
而无需转换:
Array.range(0, 15) // Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
可以从 Array
映射到 Array
,如下所示:
Array.range(0, 15).map(f) // Array[Int] = Array(0, 2, 4, 6, 8, 10, 12, 14, ...)
注意:Array.range(i, j)
等价于 i until j
(i to j+1
) 而不是 i to j
.
使用 Array.tabulate
:
甚至更短,一次通过,但可读性较差
Array.tabulate(15)(f) // Array[Int] = Array(0, 2, 4, 6, 8, 10, 12, 14, ...)
以下代码创建一个临时 Vector:
0.to(15).map(f).toArray
^^^^^^^^
Sequence
^^^^^^^^^^^^^^^
temp Vector
^^^^^^^^^^^^^^^^^^^^^^^
Array
以下代码创建一个临时数组:
0.to(15).toArray.map(f)
^^^^^^^^
Sequence
^^^^^^^^^^^^^^^
temp Array
^^^^^^^^^^^^^^^^^^^^^^^
Array
有没有办法将 f 映射到 Sequence 上并直接得到一个 Array,而不产生一个临时的?
(0 to 15).iterator.map(f).toArray
您可以使用 breakOut
:
val res: Array[Int] = 0.to(15).map(f)(scala.collection.breakOut)
或
0.to(15).map[Int, Array[Int]](f)(scala.collection.breakOut)
或使用view
:
0.to(15).view.map(f).to[Array]
有关视图的更多详细信息,请参阅 this document。
如果您了解如何构建初始 Range
,您也可以使用 Array.range(start, end)
from the Array
companion object 直接创建 Range
作为 Array
而无需转换:
Array.range(0, 15) // Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
可以从 Array
映射到 Array
,如下所示:
Array.range(0, 15).map(f) // Array[Int] = Array(0, 2, 4, 6, 8, 10, 12, 14, ...)
注意:Array.range(i, j)
等价于 i until j
(i to j+1
) 而不是 i to j
.
使用 Array.tabulate
:
Array.tabulate(15)(f) // Array[Int] = Array(0, 2, 4, 6, 8, 10, 12, 14, ...)