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

问题描述

可能的重复:
更新 Scala 案例类的操作

这个问题是今晚我想到的.

This question came to me this evening.

我有两个相同类型的实例化案例类.

I have two instantiated case classes of the same type.

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

让我们调用实例化的类 A 和 B.

Lets call the instantiated classes A and B.

val a = Foo(a=Some("foo"), b=Some("bar"), c=Some("baz"))
val b = Foo(a=None, b=Some("etch"), c=None)

我想知道是否有可能以通用方式在单个操作中用 B 更新案例类 A.

I'm wondering if its possible to update case class A with B in a single operation in a generic way.

val c = b *oper* a // Foo(a=Some("foo"), b=Some("etch"), c=Some("baz"))

忽略设置为 None 的参数.理想情况下,操作也应该是通用的,以便它可以作用于任何类型的案例类.

with parameters that are set as None ignored. Ideally the operation should also be generic so it can act on any type of case class.

我有一些直觉,可以通过首先将类转换为元组/列表并在操作完成后转换回类来使用 Scalaz 执行此操作 - 也许使用 ApplicativeBuilder?有什么想法吗?

I have some intuition that it might be possible to do this with Scalaz by converting the class into a tuple/list first and converting back to a class after the operation is complete - perhaps using the ApplicativeBuilder? Any ideas?

推荐答案

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

val a = Foo(a=Some("foo"), b=Some("bar"), c=Some("baz"))
val b = Foo(a=None, b=Some("etch"), c=None)

def op(a:Foo, b:Foo) = Foo(b.a.orElse(a.a), b.b.orElse(a.b), b.c.orElse(a.c))

op(a,b)

如果我理解正确......

If I understand you correctly......

这篇关于更新 Scala 案例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-03 11:52