Safely copying fields between case classes of different types

我是研究僧i 提交于 2019-11-28 07:02:37

In shapeless 2.0.0 this can be done with like so,

scala> import shapeless._
import shapeless._

scala> case class Test1(a: String, b: Int, c: Char)
defined class Test1

scala> case class Test2(a: String, b: Int)
defined class Test2

scala> val test1 = Test1("first", 2, '3')
test1: Test1 = Test1(first,2,3)

scala> val test2 = Test2("1st", 20)
test2: Test2 = Test2(1st,20)

scala> val test1Gen = Generic[Test1]
test1Gen: ... = $1$$1@6aac621f

scala> val test2Gen = Generic[Test2]
test2Gen: ... = $1$$1@5aa4954c

scala> val test3 = test1Gen.from(test2Gen.to(test2) :+ test1.c)
test3: Test1 = Test1(1st,20,3)

Note that this makes assumptions about the order of fields in each of the case classes rather than making use of field label information. This could be error prone where you had multiple fields of the same type: the types might line up, but the latent semantics might be altered.

We can fix that by using shapeless's LabelledGeneric. LabelledGeneric maps case class values to shapeless extensible records which, as well as capturing the types of the field values, also encodes the field names in the type by way of the singleton type of the corresponding Scala Symbol. With a little bit of additional infrastructure (which I'll be adding to shapeless 2.1.0 shortly) this allows us to map between case classes safely with minimal boilerplate,

import shapeless._, record._, syntax.singleton._, ops.hlist.Remove

/**
 * This will be in shapeless 2.1.0 ...
 *
 * Permute the elements of the supplied `HList` of type `L` into the same order
 * as the elements of the `HList` of type `M`.
 */
trait Align[L <: HList, M <: HList] extends (L => M) {
  def apply(l: L): M
}

object Align {
  def apply[L <: HList, M <: HList]
    (implicit alm: Align[L, M]): Align[L, M] = alm

  implicit val hnilAlign: Align[HNil, HNil] = new Align[HNil, HNil] {
    def apply(l: HNil): HNil = l
  }

  implicit def hlistAlign[L <: HList, MH, MT <: HList, R <: HList]
    (implicit
      select: Remove.Aux[L, MH, (MH, R)],
      alignTail: Align[R, MT]): Align[L, MH :: MT] = new Align[L, MH :: MT] {
    def apply(l: L): MH :: MT = {
      val (h, t) = l.removeElem[MH]
      h :: alignTail(t)
    }
  }
}

/**
 * This, or something like it, will be in shapeless 2.1.0 ...
 *
 * Utility trait intended for inferring a field type from a sample value and
 * unpacking it into its key and value types.
 */
trait Field {
  type K
  type V
  type F = FieldType[K, V]
}

object Field {
  def apply[K0, V0](sample: FieldType[K0, V0]) =
    new Field { type K = K0; type V = V0 }
}

object OldWineNewBottle {
  case class From(s1: String, s2: String)
  case class To(s2: String, i: Int, s1: String)

  val from = From("foo", "bar")

  val fromGen = LabelledGeneric[From]
  val toGen = LabelledGeneric[To]

  // Define the type of the i field by example
  val iField = Field('i ->> 0)

  val align = Align[iField.F :: fromGen.Repr, toGen.Repr]

  // extend the fields of From with a field for 'i', permute into
  // the correct order for To and create a new instance ...
  val to = toGen.from(align('i ->> 23 :: fromGen.to(from)))

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