Your addToCount
does not add 1 (or anything) to count. It calculates count + 1
. (Same as Java would...)
I suppose you meant this:
...
def addToCount { count += 1 }
...
Question
One of my coworkers showed me an interesting snippet where a var declared within an object was not being mutated by a member of the object. It will be great if somebody explains why is it behaving this way. The code is as follows:
object SomeObject{
var count = 1
def addToCount = count + 1
def printCurrentCount:Unit = {addToCount;println(count)}
}
// Exiting paste mode, now interpreting.
defined module SomeObject
scala> SomeObject.printCurrentCount
1
Shouldn't printCurrentCount
print out the mutated var count to be 2?
Solution
Your addToCount
does not add 1 (or anything) to count. It calculates count + 1
. (Same as Java would...)
I suppose you meant this:
...
def addToCount { count += 1 }
...