I am creating an object of a class in Scala and I would like to clone the object but change one member's value. For that I'm trying to do something like this:
abstract class A {
var dbName: String
def withConfig(db: String): A = {
var a = this
a.dbName = db
a
}
}
class A1(db: String) extends A {
override var dbName: String = db
}
class A2(db: String) extends A {
override var dbName: String = db
}
object Test {
def main(args: Array[String]): Unit = {
var obj = new A1("TEST")
println(obj.dbName)
var newObj = obj.withConfig("TEST2")
println(newObj.dbName)
println(obj.dbName)
}
}
When I run this program, I get the below output:
TEST
TEST2
TEST2
While I was able to create a new object from the original in this, unfortunately it ended up modifying the value of the member of the original object as well. I believe this is because I'm using the same instance this
and then changing the member.
Thus I thought I can clone the object instead, for which I made a change to the withConfig
method:
def withConfig(db: String): A = {
var a = this.clone().asInstanceOf[A]
a.dbName = db
a
}
Unfortunately, it is throwing an error saying Clone Not supported:
TEST
Exception in thread "main" java.lang.CloneNotSupportedException: c.i.d.c.A1
at java.lang.Object.clone(Native Method)
at c.i.d.c.A.withConfig(Test.scala:7)
at c.i.d.c.Test$.main(Test.scala:21)
at c.i.d.c.Test.main(Test.scala)
Is there a way I could achieve the functionality similar to clone()
, but without making significant changes to the abstract class?