0

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?

Community
  • 1
  • 1
Rasputin Jones
  • 1,427
  • 2
  • 16
  • 24

1 Answers1

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

xiefei
  • 6,563
  • 2
  • 26
  • 44