Scala 数组初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2614476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala array initialization
提问by Etam
You have:
你有:
val array = new Array[Array[Cell]](height, width)
How do you initialize all elements to new Cell("something")?
你如何将所有元素初始化为 new Cell("something")?
Thanks, Etam (new to Scala).
谢谢,Etam(Scala 新手)。
回答by Eastsun
Welcome to Scala version 2.8.0.r21376-b20100408020204 (Java HotSpot(TM) Client VM, Java 1.6.0_18).
Type in expressions to have them evaluated.
Type :help for more information.
scala> val (height, width) = (10,20)
height: Int = 10
width: Int = 20
scala> val array = Array.fill(height, width){ new Cell("x") }
array: Array[Array[Cell[java.lang.String]]] = Array(Array(Cell(x), Cell(x), ...
scala>
回答by Etam
val array = Array.fill(height)(Array.fill(width)(new Cell("something")))
回答by sepp2k
val array = Array.fromFunction((_,_) => new Cell("something"))(height, width)
Array.fromFunction accepts a function which takes n integer arguments and returns the element for the position in the array described by those arguments (i.e. f(x,y) should return the element for array(x)(y)) and then n integers describing the dimensions of the array in a separate argument list.
Array.fromFunction 接受一个函数,该函数接受 n 个整数参数并返回由这些参数描述的数组中位置的元素(即 f(x,y) 应返回 array(x)(y) 的元素),然后返回 n 个整数在单独的参数列表中描述数组的维度。
回答by Daniel C. Sobral
Assuming the array has already been created, you can use this:
假设已经创建了数组,你可以使用这个:
for {
i <- array.indices
j <- array(i).indices
} array(i)(j) = new Cell("something")
If you can initialize at creation, see the other answers.
如果您可以在创建时进行初始化,请参阅其他答案。

