Reputation: 15788
Does scala support memberwise assignment?
Given:
case class C(var x:Int, var y:Int)
val c = C(1,2)
val d = C(3,4)
is there an operator to assign each member of d to c.
In C/C++ you would have:
struct C{ int x, int y)
C c = {1,2}
C d = {3,4}
c = d
edit1
One of the great benefits of member-wise assignment is that its automatic, in
Both
c() = d
and
c.copyFrom( d )
both suffer from a maintenance problem - if new members are added members to C its easy to overlook adding the member to the user-created function. What's really desired is automated way to copy these values.
edit2
Another use case for this behavior:
val props:ThirdPartyType = ThirdPartyLibrary.getProperties()
val myprops:ThirdPartyType = MyLibrary.loadPropertiesFromFile()
props @= myprops // magic member-wise assignment
Here we may find:
I can do:
props.a = myprops.a
props.b = myprops.b
...
but this pattern break when we update to V2 of the ThirdParty library. ThirdPartyType has gained new members that we didn't not copy.
Can't this be solved through reflection?
Upvotes: 1
Views: 123
Reputation: 39577
The enhancement is easy:
scala> :pa
// Entering paste mode (ctrl-D to finish)
case class C(var x:Int, var y:Int)
val c = C(1,2)
val d = C(3,4)
// Exiting paste mode, now interpreting.
defined class C
c: C = C(1,2)
d: C = C(3,4)
scala> implicit class CUpdater(val c: C) { def update(d: C) = { c.x=d.x ; c.y=d.y } }
defined class CUpdater
scala> c() = d
scala> c
res1: C = C(3,4)
Usual caveats around mutability apply. And you didn't hear it from me.
Upvotes: 5
Reputation: 33063
This will get you a separate object with all case class constructor arguments copied over, although it will not change the original object that d
pointed to:
d = c.copy()
If you really want to modify the original object that d
points to (perhaps because you have a reference to it somewhere else - think of pointers to structs in the C programming language), then I think you would have to do something fancy with metaprogramming (i.e. reflection or macros) to get a general solution for this.
But I recommend programming with immutable val
s, almost always! If you can live with that, copy
is fine.
Upvotes: 3