Mutable Map as parameter of a class

I defined the following class with a mutable map as parameter:

import scala.collection.mutable.{Map => MMap}

class CC(private var _cs: MMap[Double, Int]) {
    def cs = _cs
	
	implicit val order = Ordering.Double.TotalOrdering

    def decrement(c: Double): Unit = {
      if (_cs(c) == 1)
        _cs -= (c, _cs(c))
      else
        _cs(c) -= 1
    }

    val maxKey: Double = _cs.keys.max
}

When defining

val m = new CC( MMap[Double,Int]( 4.0 -> 3, 5.1 -> 1, 2.2 -> 4) )

and executing

m.maxKey

(with result 5.1)

and then executing

m.decrement

I still get for m.maxKey the result 5.1 though 5.1 is no longer a key of m

as m.cs gives

scala.collection.mutable.Map[Double,Int] = HashMap(2.2 -> 4, 4.0 -> 3)

What is wrong with my code?
Thanks in advance!

change the val to a def. vals are computed once eagerly. defs are computed each time

Thank you for your helpful advice.

Additionally, it’s odd to have a mutable map in a var. You probably either want a mutable map in a val or an immutable map in a var.

2 Likes