合并两个相同类型的 case 类,除了一些字段 [英] Merge two case class of same type, except some fields

查看:42
本文介绍了合并两个相同类型的 case 类,除了一些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个像这样的案例类:

If you have a case class like:

case class Foo(x: String, y: String, z: String)

您有两个实例,例如:

Foo("x1","y1","z1")
Foo("x2","y2","z2")

是否可以将实例 1 合并到实例 2 中,除了字段 z,结果是:

Is it possible to merge instance 1 in instance 2, except for field z, so that the result would be:

Foo("x1","y1","z2")

<小时>

我的用例只是我通过 Scala API 将 JSON 对象提供给 Backbone 应用程序,而 Backbone 应用程序返回一个相同结构的 JSON,以便我可以保存/更新它.这些 JSON 对象被解析为 case 类,以便于 Scala 操作.但是有些字段不应该被客户端更新(比如creationDate).目前我正在手动合并,但我想要一个更通用的解决方案,有点像增强的复制功能.


My usecase is just that I give JSON objects to a Backbone app through a Scala API, and the Backbone app gives me back a JSON of the same structure so that I can save/update it. These JSON objects are parsed as case class for easy Scala manipulation. But some fields should never be updated by the client side (like creationDate). For now I'm doing a manual merge but I'd like a more generic solution, a bit like an enhanced copy function.

我想要的是这样的:

instanceFromDB.updateWith(instanceFromBackbone, excludeFields = "creationDate" )

但我希望它是类型安全的 :)

But I'd like it to be typesafe :)

我的案例类有更多的字段,我希望默认行为合并字段,除非我明确说不合并它们.

My case class have a lot more fields and I'd like the default bevavior to merge fields unless I explicitly say to not merge them.

推荐答案

你想要的已经有了;你只需要换一种方式来解决问题.

What you want is already there; you just need to approach the problem the other way.

case class Bar(x: String, y: String)
val b1 = Bar("old", "tired")
val b2 = Bar("new", "fresh")

如果你想要b2中没有特别提到的所有内容,你应该从b2复制;b1 中您想保留​​的任何内容都可以明确提及:

If you want everything in b2 not specifically mentioned, you should copy from b2; anything from b1 you want to keep you can mention explicitly:

def keepY(b1: Bar, b2: Bar) = b2.copy(y = b1.y)

scala> keepY(b1, b2)
res1: Bar = Bar(new,tired)

只要您在同一个 case 类的两个实例之间进行复制,并且字段是不可变的,就像默认情况下一样,这将满足您的需求.

As long as you are copying between two instances of the same case class, and the fields are immutable like they are by default, this will do what you want.

这篇关于合并两个相同类型的 case 类,除了一些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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