1

As said in the title, I can't reassign a variable of type Arraybuffer(Arraybuffer(Int,Int),Int) in a for loop:

var ab1 = ArrayBuffer(le4: _*)
var ab2 = ab1 map (ligne => (ArrayBuffer(ligne._1: _*), ligne._2))
println("ab:" + ab2)

for {
    i <- 1 to ab2.length
    j <- 0 to i
} {
    ab2(i)._1(j)._2 = j match {
        case 0 =>  ab2(i - 1)._1(0)._2 + ab2(i)._1(j)._1
        case i =>  ab2(i - 1)._1(j - 1)._2 + ab2(i)._1(j)._1
        case _ =>  ab2(i - 1)._1(j)._2 + ab2(i - 1)._1(j - 1)._1 + ab2(i)._1(j)._1
    }
}

the key point is that ab2 is declared as var but the change of an Int inside it is denied. Why?

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
lolveley
  • 1,659
  • 2
  • 18
  • 34
  • possible duplicate of [What is the difference between a var and val definition in Scala?](http://stackoverflow.com/questions/1791408/what-is-the-difference-between-a-var-and-val-definition-in-scala) – senia Sep 26 '13 at 12:10

1 Answers1

6

There's a difference between a var, and a mutable object.

  • var can have its value reassigned at will
  • a mutable object can have its fields reassigned. Like an object with vars in it

You are trying to set the _2 field of a tuple inside of ab2; tuples are immutable, and that's why it causes a compiler error.

Reconsider the data structure you're using for this operation. A collection.mutable.Map might be better, or anything else that has an update method which allows you to change values inside of it.

Dylan
  • 13,645
  • 3
  • 40
  • 67