带有可选值的Scala案例类副本 [英] Scala case class copy with optional values

查看:33
本文介绍了带有可选值的Scala案例类副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制一个案例类,用第二个案例类中的可选值更新它.

I want to make a copy of a case class, updating it with optional values from a second case class.

case class A(
  id: Int,
  a: String,
  b: String,
  c: String)

case class Update(
  a: Option[String],
  b: Option[String],
  c: Option[String])

复制 A 的最有效方法是什么,使用 Update 中不是 None 的值更新字段?如果可能,我想避免在 Update 中创建涉及 Some/None 值的所有可能排列的 match/case 语句.

What is the most efficient way that I can make a copy of A, updating the fields with values from Update that are not None? I want to avoid making a match/case statement involving all possible permutations of Some/None values in Update, if possible.

推荐答案

简单:

val originalA: A = // ...
val update: Update = // ...
val newA: A = A(
  id = originalA.id,
  a = update.a.getOrElse(originalA.a),
  ...
)

这篇关于带有可选值的Scala案例类副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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