how do I increment an integer variable I passed into a function in Scala?

immutability, parameter-passing, scala

Solution

First of all, I will repeat my words of caution: solution below is both obscure and inefficient, if it possible try to stick with `val`ues.

implicit class MutableInt(var value: Int) {
  def inc() = { value+=1 } 
}

def function(s: MutableInt): Boolean={
   s.inc() // parentheses here to denote that method has side effects
   return true
}

And here is code in action:

scala> val x: MutableInt = 0 
x: MutableInt = MutableInt@44e70ff

scala> function(x)
res0: Boolean = true

scala> x.value
res1: Int = 1

Problem

I declared a variable outside the function like this: ``` var s: Int = 0 ``` passed it such as this: ``` def function(s: Int): Boolean={ s += 1 return true } ``` but the error lines wont go away under the "s +=" for the life of me. I tried everything. I am new to Scala btw.

Original source

Related problems