Eta*_*tam 13 arrays scala initialization
你有:
val array = new Array[Array[Cell]](height, width)
Run Code Online (Sandbox Code Playgroud)
如何将所有元素初始化为新Cell("某物")?
谢谢,Etam(Scala新手).
Eas*_*sun 19
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>
Run Code Online (Sandbox Code Playgroud)
Eta*_*tam 16
val array = Array.fill(height)(Array.fill(width)(new Cell("something")))
Run Code Online (Sandbox Code Playgroud)
val array = Array.fromFunction((_,_) => new Cell("something"))(height, width)
Run Code Online (Sandbox Code Playgroud)
Array.fromFunction接受一个函数,该函数接受n个整数参数并返回由这些参数描述的数组中的位置元素(即f(x,y)应该返回数组(x)(y)的元素)然后是n个整数在单独的参数列表中描述数组的维度.
假设已经创建了数组,您可以使用:
for {
i <- array.indices
j <- array(i).indices
} array(i)(j) = new Cell("something")
Run Code Online (Sandbox Code Playgroud)
如果您可以在创建时初始化,请参阅其他答案.