Reputation: 154
class x(x:int){val y=x}
class z {
val grid= Array.ofDim(8,8)
}
Is that object already initialized? when i try to initialize in loop like
for(i<-0 until 8;j<-0 until 8) grid(i)(j)=new x(someValue)
i am getting error: Null pointer exception
Upvotes: 0
Views: 351
Reputation: 8996
Arrays are by definition mutable in Scala. They are essentially Java arrays enhanced with a lot of Scala's cool Collection APIs.
The main issue with what you have is the missing type parameterization of the Array. By specifying that the Array is of type [X]
then the following code works great for me:
class X(x:Int){val y=x}
class Z {
val grid= Array.ofDim[X](8,8)
for(i<-0 until 8;j<-0 until 8) grid(i)(j)=new X(2)
}
Upvotes: 0
Reputation: 16324
You can use Array.fill
:
Array.fill(8, 8)(myValue)
Or you can use toArray
with a nested for
comprehension:
{
for {
i <- 0 until 8
} yield { for {
j <- 0 until 8
} yield myValue
}.toArray }.toArray
Similarly, you can use toArray
with map
:
(0 until 8).map { _ => (0 until 8).map { _ => myValue }.toArray }.toArray
You could also use some combination of these approaches:
Array.fill(8){ { for(_ <- (0 until 8)) yield myValue }.toArray }
Upvotes: 1