Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

scala - Safely copying fields between case classes of different types

Assuming you have case classes like the following

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

case class Test2(a:String,b:Int)

And you instantiate the classes with the following variables

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

val test2 = Test2("1st",20)

Is there a way to use the .copy method (or otherwise), to apply the variables inside Test2 to Test1, something like

val test3 = test1.copy(test2) //Note this isn't valid scala code
// Result should be ("1st",20,'3')

If this isn't possible in pure scala, how would it be done in Shapeless 1/2 (current code is in Shapeless 1, however we are planning to upgrade to Shapeless 2 at some point in time)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...