Scala:将通用案例类复制到另一个案例类中 [英] Scala: Copying a generic case class into another

查看:86
本文介绍了Scala:将通用案例类复制到另一个案例类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下设置,我要将baseData的实例复制到moreData的实例:

I have the following setup, where I want to copy an instance of baseData into that of moreData:

sealed trait baseData {
  def weight: Int
  def priority: Int
} 

sealed trait moreData {
  def weight: Int
  def priority: Int
  def t: String
  def id: String
} 

case class data1(override val weight: Int, override val priority: Int) extends baseData 
case class moreData1 (override val weight:Int, override val priority: Int, override val t: String, override val id: String)extends moreData

因此将myData复制到下面的otherData中:

So copying myData into otherData below:

val myData = data1(1,1) 
val otherData = moreData1 (2,2,"C","abcd") 

将产生:moreData1(1,1,"C","abcd").

为此,我想使用具有以下签名的函数,因为我将有多个case类扩展baseDatamoreData:

To do this, I want to use a function with the following signature, because I will have more than one case class extending both baseData and moreData:

def copyOver[A <:baseData, B <:moreData](from: A, to: B) = {} 

我确定您可以使用 Shapeless ,但尚未弄清楚如何做.有示例(此处)复制具有相同特征的案例类,以及其他(

I'm sure you can do this with Shapeless, but haven't figured out how. There are examples (here) on copying case classes extending a same trait, and others (here) mapping values between different case classes via generic representation. But I haven't figured out how to use LabelledGeneric with the trait-bounded arguments passed into copyOver. I also don't want to have to hardcode the extra fields in otherData that aren't present in myData.

我正在寻找一个完全通用的实现.有什么想法吗?

I'm looking for a completely generic implementation. Any ideas?

推荐答案

您应该能够使用您可以使用UpdateRepr定义copyOver,如下所示:

You could define copyOver using UpdateRepr as follows :

import shapeless._

// baseData, moreData, data1, moreData1
// UpdateRepr ...

def copyOver[A <: baseData, B <: moreData, R <: HList](
  from: A,
  to: B
)(implicit 
  lgen: LabelledGeneric.Aux[A, R],
  update: UpdateRepr[B, R]
): B = update(to, lgen.to(from))

您可以如下使用:

val myData = data1(1,1) 
val otherData = moreData1(2,2,"C","abcd") 

copyOver(myData, otherData)
// moreData1 = moreData1(1,1,C,abcd)

请注意,由于UpdateRepr的密封特征(副产品)类型类派生,您可能会遇到SI-7046问题,您可能会在REPL中或拆分UpdateRepr和密封特征时注意到这一点多个文件.

Note that it is possible you run into problems with SI-7046, because of the sealed trait (Coproduct) type class derivation for UpdateRepr, which you could notice in the REPL or when splitting UpdateRepr and the sealed traits over multiple files.

这篇关于Scala:将通用案例类复制到另一个案例类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆