本文介绍了带有可选值的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案例类副本
发布评论