带有可选值的Scala案例类副本

编程入门 行业动态 更新时间:2024-10-27 08:27:07
本文介绍了带有可选值的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案例类副本

本文发布于:2023-07-14 22:16:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107329.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   副本   案例   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!