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?

有帮助吗?

解决方案

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 }
...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top