创建一个generalize方法而不会丢失类型

时间:2015-07-27 14:43:58

标签: scala scalaz shapeless

我们有

private def insertUpdateDeleteFormDsList(dsList : List[FormDefinitionDataSourceRequestModel])(implicit formDefId:Int,subject:Subject,session: Session) : (List[(Int,Int)],Seq[FormDefinitionDataSourceRequestModel],Seq[FormDefinitionDataSourceRequestModel]) = {
val incomingIds = dsList.map( ds => (ds.dataSourceId,ds.dsTypeId) )

val existingIds = formDefinitionDatasources.filter(_.tenantId === subject.tenantId).filter(_.formDefId === formDefId).map( ds => (ds.dataSourceId,ds.dataSourceTypeId) ).list

val idsForDeletion = existingIds diff incomingIds
val idsForInsertion = incomingIds diff existingIds
val idsForUpdate = existingIds diff idsForDeletion


val insertList = dsList.flatMap{ t => idsForInsertion collectFirst{ case (dsId,dsType) if(dsId == t.dataSourceId && dsType == t.dsTypeId)=> t} }
val updateList = dsList.flatMap{t=>idsForUpdate collectFirst {case (dsId,dsType) if(dsId == t.dataSourceId && dsType == t.dsTypeId)=> t}}

(idsForDeletion,updateList,insertList)

}

和其他类似的方法

private def insertUpdateDelDataInstances(instances: List[Instance])(implicit subject: Subject, session: Session): (Seq[Instance], Seq[Instance], Seq[Instance]) = {
val incomingIds = instances.map(_.id)
val existingIds = dataSourceInstanceNew.filter(_.tenantId === subject.tenantId).map(_.id).list
val idsForDeletion = existingIds diff incomingIds
val idsForInsertion = incomingIds diff existingIds
val idsForUpdate = existingIds diff idsForDeletion

val deleteList = instances.flatMap{ t => idsForDeletion collectFirst{ case id if(id == t.id)=> t} }
val insertList = instances.flatMap{ t => idsForInsertion collectFirst{ case id if(id == t.id)=> t} }
val updateList = instances.flatMap{t=>idsForUpdate collectFirst {case id if(id === t.id)=> t}}
(deleteList,updateList,insertList)
}

其他地方也有类似的方法。每次List[T]作为方法参数传递时,T始终为case class。现在如何构造val incomingIds依赖于特定的case class属性。

我们想要创建一个通用函数,它可以接受List[T]incomingIds并返回一个所需的元组,以避免每次都写出类似的样板文件。

如果说逻辑是"总是"使用T case class' id属性,然后我可以使用trait轻松创建父id并使所有case class es mixin特质 - 但事实并非如此。准备val incomingIds取决于不同的case class属性,具体取决于从中调用代码的位置。

以下说明

def generalizedInsertUpdateDeleteList[T](data:List[T],incomingIds:List[Int], existingIds:List[Int] )(implicit subject: Subject, session:Session) = {
val idsForDeletion = existingIds diff incomingIds
val idsForInsertion = incomingIds diff existingIds
val idsForUpdate = existingIds diff idsForDeletion

/*
//what's the best way to generalize comparison inside  collectFirst?
//to use case class attribute names from `T`. Was thinking if Structural type can help but not sure if that
//can quite work unless there is a way to pass in arguments in a structural type? 


val deleteList = data.flatMap{ t => idsForDeletion collectFirst{ case id if(id == t.id)=> t} }
val insertList = data.flatMap{ t => idsForInsertion collectFirst{ case id if(id == t.id)=> t} }
val updateList = data.flatMap{ t => idsForUpdate collectFirst {case id if(id === t.id)=> t}}
*/

如果没有其他更简洁的方法来使用标准的scala / scalaz API实现这一点,那么这里可以提供无形的帮助吗?

3 个答案:

答案 0 :(得分:3)

Shapeless的记录提供了一种类型安全的方法来抽象具有特定成员名称的案例类。例如:

import shapeless._, ops.record.Selector

def getId[A, R <: HList](a: A)(implicit
  gen: LabelledGeneric.Aux[A, R],
  sel: Selector[R, Witness.`'id`.T]
): sel.Out = sel(gen.to(a))

然后:

scala> case class Foo(id: String)
defined class Foo

scala> case class Bar(id: Int, name: String)
defined class Bar

scala> getId(Foo("12345"))
res0: String = 12345

scala> getId(Bar(123, "bar"))
res1: Int = 123

如果您需要约束id成员的类型,可以使用Selector.Aux

def getIntId[A, R <: HList](a: A)(implicit
  gen: LabelledGeneric.Aux[A, R],
  sel: Selector.Aux[R, Witness.`'id`.T, Int]
): Int = sel(gen.to(a))

现在getIntId(Bar(123, "bar"))会编译,但getIntId(Foo("12345"))不会。

答案 1 :(得分:1)

您可以创建一个PartialFunction的类型类,可以在collectFirst中使用。

trait IUD[T, IdType] {
  // returns a partial function which will be used in collectFirst
  def collectId(t: T): PartialFunction[IdType, T]
}

我们可以为您的两种方法创建IUD个实例:

// I chose (Long, Long) as type of (ds.dataSourceId,ds.dsTypeId) 
type FormModel = FormDefinitionDataSourceRequestModel
implicit object FormModelIUD extends IUD[FormModel, (Long, Long)] {
  def collectId(t: FormModel): PartialFunction[(Long, Long), FormModel] = {
    case (dsId,dsType) if(dsId == t.dataSourceId && dsType == t.dsTypeId) => t
  }
}

implicit object InstanceIUD extends IUD[Instance, Int] {
  def collectId(t: Instance): PartialFunction[Int, Instance] = {
    case id if id == t.id => t
  }
}

我们可以在IUD方法中使用generalizedInsertUpdateDeleteList类型:

def generalizedIUDList[T, IdType](
  data: List[T], incomingIds: List[IdType], existingIds: List[IdType]
)(implicit 
  subject: Subject, session: Session, iud: IUD[T, IdType]
) = {
  val idsForDeletion = existingIds diff incomingIds
  val idsForInsertion = incomingIds diff existingIds
  val idsForUpdate = existingIds diff idsForDeletion

  def filterIds(ids: List[IdType]) = 
    data.flatMap(instance => ids collectFirst(iud.collectId(instance)) )

  val deleteList = filterIds(idsForDeletion)
  val insertList = filterIds(idsForInsertion)
  val updateList = filterIds(idsForUpdate)

  (deleteList,updateList,insertList)
} 

答案 2 :(得分:0)

collectFirst接受PartialFunction,在您的情况下PartialFunction[Int, T]我认为?

您可以将部分函数作为参数传递给generalizedInsertUpdateDeleteList方法,然后每次只需要定义这些函数。