i have a class Demo i want to save object value before setting attribute value here 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 on the console is
old name is joe the new name is joe
i want to store object value before setting d.abc="joe"
so that i can get bob
when i do oldDemo.abc
please guide me where i am going wrong and what is the right way to achieve my goal .and i apologize if i am doing something stupid
You can use copy()
on a case class.
val d1 = Demo("abc")
val d2 = d1.copy()
d1.abc = "def"
// d2 : Demo = Demo(abc)
// d1 : Demo = Demo(def)
A more Scala idiomatic 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)