scala是否支持成员分配?
鉴于:
case class C(var x:Int, var y:Int) val c = C(1,2) val d = C(3,4)
是否有运营商将d的每个成员分配给c.
在C/C++中你会得到:
struct C{ int x, int y) C c = {1,2} C d = {3,4} c = d
EDIT1
成员分配的最大好处之一是它的自动化
都
c() = d
和
c.copyFrom( d )
两者都有维护问题 - 如果新成员被添加到C成员,很容易忽略将成员添加到用户创建的功能.真正需要的是自动复制这些值的方法.
EDIT2
此行为的另一个用例:
val props:ThirdPartyType = ThirdPartyLibrary.getProperties() val myprops:ThirdPartyType = MyLibrary.loadPropertiesFromFile() props @= myprops // magic member-wise assignment
在这里我们可以找到:
我们坚持使用ThirdPartyLibrary和ThirdPartyType(无法更改)
该库不提供重新分配属性对象的功能.
该库确实提供了分配属性值的功能.它表现为具有公共成员的JavaBean POJO.
我可以:
props.a = myprops.a props.b = myprops.b ...
但是当我们更新到ThirdParty库的V2时,这种模式会中断.ThirdPartyType获得了我们没有复制的新成员.
这不能通过反思来解决吗?
增强很容易:
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)
关于可变性的常见警告适用.你没有听到我的消息.