xrs
xrs

Reputation: 154

scala: Initialization of array of immutable objects

    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

Answers (3)

marios
marios

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

Ben Reich
Ben Reich

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

synapse
synapse

Reputation: 5728

Use Array.fill like this val grid = Array.fill(8, 8) { new X(1) }

Upvotes: 2

Related Questions