1

I'm a new Scala fellow and using processing library in scala ,I have 2 questions here:

 val grid: Array[Cell] = Array()              
 val w = 60   
 val rows = height/w   
 val cols = width /w

 override def setup(): Unit = {  
   for(j <- 0 until rows;   
       i <- 0 until cols){   
   val cell = new Cell(i,j)   
   grid :+ cell   
   println(s"at row : $j, at col: $i") //it compiles only once (at row : 0, 
   }                                    //at col: 0 )                                          
}
override def draw(): Unit = {
  background(0)
  grid.foreach(cell => cell.display())//nothing happens
} 

but if i replace the variables rows & cols by height/w & width/w in the nested loop as follows:

     for(j <- 0 until height/w;   
         i <- 0 until width/w){   
     val cell = new Cell(i,j)   
     grid :+ cell   
     println(s"at row : $j, at col: $i") //it compiles ordinary as nested 
        }                                 //for loop 

the second question is in the class Cell here:

   class Cell(i: Int,j:Int){

     def display(): Unit = {
       val x = this.i * w
       val y = this.j * w

       println("it works")//doesn't work
       //creating a square
       stroke(255)
       line(x,y,x+w,y)//top
       line(x+w,y,x+x,y+w)//right
       line(x,y+w,x+w,y+w)//bottom
       line(x,y,x,y+w)//left

   }
 }

the method display doesn't work when calling at function draw() but no errors show up

5
  • Hi, Array() in scala is unmutable. By doing grid :+ cell you just create a new Array with that value, but do not add this value to the grid array. You need to use scala.collection.mutable.ArrayBuffer[Cell]() instead and add the values using += Commented Sep 13, 2018 at 10:12
  • Your loop looks good. I can assume that your height and width values are too small. Commented Sep 13, 2018 at 10:52
  • thanks dyrkin it really helped Commented Sep 13, 2018 at 10:55
  • Another way would be to use var grid: Array[Cell] = Array() and then grid :+= cell Commented Sep 13, 2018 at 11:04
  • 1
    "Array() in scala is unmutable" — to be more specific: on the JVM (including in Scala) an array is always a fixed size. They are otherwise mutable (that is, individual elements can be replaced). Commented Sep 13, 2018 at 20:20

1 Answer 1

1

Use tabulate to initialise your Array:

val grid = Array.tabulate(rows * cols) { i => new Cell(i % cols, i / cols) }

If you still have a problem with the display function then please post it as a separate question.

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

Comments

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.