Assuming that I have a Scala case class like the following:
case class Item(
roundedValue: Double = 0.00)
I want to perform the following rounding operation on roundedValue every time the variable is updated:
roundedValue = math.round(roundedValue*100)*0.01
In other languages I would just override the setter for roundedValue, but it appears that I cannot override the setter for a case class variable or it won’t compile.
One solution I have seen is to rename roundedValue to _roundedValue and make it private, and then add public methods to simulate getter and setter (with rounding logic): Overriding setter on var
However this makes constructor usage pretty awkward for the case class when using named parameters. Is there any other way to do this, or is this a limitation of case classes in Scala?
If you can make it work, I would recommend keeping your case class immutable, but making a “copy” method that does your mutations on a new instance.
You may also/instead want to have a similar method in the companion object: