How to save the state of an object before and after setting attribute values
I have a Demo class, I want to store the object value before setting the attribute value here, this is my code
case class Demo (var abc:String)
val d =Demo("bob")
var oldDemo=d
d.abc="joe"
println("old name is "+oldDemo.abc +" the new name is "+d.abc)
the output printed to the console
old name is joe the new name is joe
I want to store the value of the object before setting d.abc="joe"
so that I can get bob
when I do oldDemo.abc
please tell me where I am going wrong and what is the correct way to achieve my goal. And I am sorry if I am doing something stupid.
source to share
You can use copy()
case for class.
val d1 = Demo("abc")
val d2 = d1.copy()
d1.abc = "def"
// d2 : Demo = Demo(abc)
// d1 : Demo = Demo(def)
A more idiomatic Scala way would be to use immutable case classes:
case class Person(name: String, age: Int)
val bob = Person("Bob", 30)
val joe = bob.copy(name="Joe")
// bob : Person = Person(Bob,30)
// joe : Person = Person(Joe,30)
source to share
- afaik, case classes should be immutable.
- class classes are cheap, so an immutable case class might suit your requirements.
- If you are modifying a mutable object, referencing that object will not help you keep the previous state. To do this, you will need a copy of this object.
So, depending on your requirements, I would either copy the original object by changing the selection attributes so that qasi mutate it
case class Demo(abc: String)
val demo = Demo("foo")
val quasiMutatedDemo = demo.copy(abc = "bar")
or I would have to implement a copy in my mutable class (simply because I just couldn't bring myself to create a mutable case class).
class Demo(var abc: String) {
def copy: Demo = new Demo(this.abc)
}
val demo = new Demo("foo")
val odlDemo = demo.copy
val mutatedDemo = demo.abc = "bar"
source to share