likern
likern

Reputation: 3964

Convert between case classes with same structure

I have two identical case classes, let's say

case class JsonOutput(
  creationDate: ZonedDateTime,
  updateDate: ZonedDateTime,
  doctorName: String,
  patientName: String,
  userName: String
)

and

case class DbOutput(
  creationDate: ZonedDateTime,
  updateDate: ZonedDateTime,
  doctorName: String,
  patientName: String,
  userName: String
)

which structurally are the same, but doesn't have some relation (and their similarity might be changed in the future)

I want to convert DbOutput type which I get from database to JsonOutput, which later I'll use for convertion (by Play Json) like

//fullCase is of type JsonOutput
Ok(Json.obj("case" -> fullCase))

How I would do this?

Note:

And what to do in case of nested case class structure:

case class GeneralInfo(number: Int)

// Nested case class structure
case class JsonOneOutput(text: String)
case class JsonThreeOutput(meta: JsonOneOutput, info: GeneralInfo)

// Nested case class structure    
case class DbOneOutput(text: String)
case class DbThreeOutput(meta: DbOneOutput, info: GeneralInfo)

where I again have to convert DbOutput to JsonOutput (and all types are the same, except some leaf node type like DbOneOutput and JsonOneOutput, which can be at deep level)

Upvotes: 1

Views: 77

Answers (1)

Denis Rosca
Denis Rosca

Reputation: 3469

You seem to want to do this with shapeless so I would suggest you take a look at the documentation. A example of how this could be achieved is:

import shapeless.Generic

object FooBar {

  case class Foo(a: String, b: Int, c: String)
  case class Bar(x: String, y: Int, z: String)

  def main(args: Array[String]): Unit = {
    val genFoo = Generic[Foo]
    val genBar = Generic[Bar]

    println(genBar.from(genFoo.to(Foo("foobar", 5, "barfoo"))))
  }

}

Upvotes: 1

Related Questions