如何克隆案例类实例并仅更改 Scala 中的一个字段? [英] How to clone a case class instance and change just one field in Scala?

查看:34
本文介绍了如何克隆案例类实例并仅更改 Scala 中的一个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个案例类,它代表不同社交网络上的人物角色.该类的实例是完全不可变的,并保存在不可变集合中,最终由 Akka actor 进行修改.

Let's say I have a case class that represents personas, people on different social networks. Instances of that class are fully immutable, and are held in immutable collections, to be eventually modified by an Akka actor.

现在,我有一个包含许多字段的案例类,我收到一条消息,说我必须更新其中一个字段,如下所示:

Now, I have a case class with many fields, and I receive a message that says I must update one of the fields, something like this:

case class Persona(serviceName  : String,
                   serviceId    : String,
                   sentMessages : Set[String])

// Somewhere deep in an actor
val newPersona = Persona(existingPersona.serviceName,
                         existingPersona.serviceId,
                         existingPersona.sentMessages + newMessage)

注意我必须指定所有字段,即使只有一个更改.有没有办法克隆 existingPersona 并只替换一个字段,而不指定所有不更改的字段?我可以把它写成一个特征并将它用于我所有的案例类吗?

Notice I have to specify all fields, even though only one changes. Is there a way to clone existingPersona and replace only one field, without specifying all the fields that don't change? Can I write that as a trait and use it for all my case classes?

如果 Persona 是一个类似 Map 的实例,那将很容易做到.

If Persona was a Map-like instance, it would be easy to do.

推荐答案

case class 附带一个 copy 方法,专门用于此用法:

case classcomes with a copy method that is dedicated exactly to this usage:

val newPersona = existingPersona.copy(sentMessages = 
                   existingPersona.sentMessages + newMessage)

这篇关于如何克隆案例类实例并仅更改 Scala 中的一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆