Updating a scala case class [duplicate]

拜拜、爱过 提交于 2019-12-11 14:11:36

问题


Possible Duplicate:
Update operations on a Scala Case Class

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])

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)

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"))

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.

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?


回答1:


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......



来源:https://stackoverflow.com/questions/11430109/updating-a-scala-case-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!