0
    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

1
  • Btw, class Foo(x: Int) {val y=x } and class Foo(val y: Int) are essentially the same Commented Jul 10, 2015 at 14:30

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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 }

Comments

0

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)
}

4 Comments

i specified type parameter, still same problem, I have initial some parts of array with one value and remaining parts with other value. It is working when using var, but i don't want to use var
Can you add the exact code you have or something closer to how you populate the array? Var or Val should not make much difference in this setting.
i have a 2d array of objects. i have to initialize some parts of array by randomization first, then remaining parts depending on those earlier initialized parts. for(i<-0 until 8){
the way i am initializing object in loop, is it correct or not? because i am not able to. just like loop, i first have to initialize 4 objects randomly. In am simple loop counting to 4 randomly generating x and y and passing it as grid(x)(y)=new Object(params). i also have to check that, if that object is already initialized or not. if it is already initialized then generate new x and y and generate a new object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.