chimney icon indicating copy to clipboard operation
chimney copied to clipboard

Question: Transformer from > 1 case classes to another

Open alexklibisz opened this issue 3 years ago • 1 comments

Hi - first, I've gotten a lot of value from this project. Your work is much appreciated.

My question: is it possible to have a Transformer that combines 2 (or more) case classes into a third case class? I've found this would be particularly useful when working with case classes representing normalized database rows. I often have a FooRow and a BarRow which I want to combine into a BazDto.

alexklibisz avatar May 03 '21 00:05 alexklibisz

it would be cool if the patching could be combined with transformation somehow, like: person.into[Employee].withPatch(companyDetails).transform

rogern avatar May 04 '22 14:05 rogern

One approach that seems to work is to just pack the source types into a tuple and build a transformer for the tuple:

import io.scalaland.chimney.Transformer
import io.scalaland.chimney.dsl._

final case class Foo(a: String, b: String)
final case class Bar(c: String)
final case class FooBar(a: String, b: String, c: String)

implicit val fooAndBarToFooBar: Transformer[(Foo, Bar), FooBar] = {
    case (foo, bar) =>
      foo
        .into[FooBar]
        .withFieldConst(_.c, bar.c)
        .transform
  }

val f  = Foo("a", "b")
val b  = Bar("c")
val fb = (f, b).transformInto[FooBar]
println(fb)

alexklibisz avatar May 15 '23 16:05 alexklibisz

It's a duplicate of #115, so all suggestions and ideas ca be posted there.

MateuszKubuszok avatar Aug 29 '23 11:08 MateuszKubuszok