Vikas Pandya
Vikas Pandya

Reputation: 1988

Create a generalize method without losing types

we have

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)

}

And other similar methods as

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

There are similar method occurrences elsewhere. Every time List[T] will be passed as a method argument where T is always a case class. now how val incomingIds gets constructed is dependent on specific case class attributes.

We want to create a generalized function which can accept a List[T] and possibly incomingIds and return a desired tuple to avoid writing similar looking boilerplate every time.

If say logic was to "always" use T case class 's id attribute then I can easily create a parent trait with id and have all case classes mixin the trait - but that's not the case here. preparing val incomingIds depend on different case class attributes depending on where in the code they are called from.

Illustrating below

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}}
*/

Can shapeless help here if no other cleaner way to achieve this using standard scala/scalaz APIs?

Upvotes: 2

Views: 121

Answers (3)

Peter Neyens
Peter Neyens

Reputation: 9820

You could create a type class with a PartialFunction which can be used inside collectFirst.

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

We can create IUD instances for your two methods :

// 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
  }
}

We can use the IUD type class in your generalizedInsertUpdateDeleteList method :

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

Upvotes: 1

mattinbits
mattinbits

Reputation: 10428

collectFirst accepts a PartialFunction, in your case PartialFunction[Int, T] I think?

You could pass the partial functions in as parameters to your generalizedInsertUpdateDeleteList method, then only these would need to be defined each time.

Upvotes: 0

Travis Brown
Travis Brown

Reputation: 139048

Shapeless's records provide a type-safe way to abstract over case classes with a particular member name. For example:

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

And then:

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

If you need to constrain the type of the id member, you can use 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))

Now getIntId(Bar(123, "bar")) will compile, but getIntId(Foo("12345")) won't.

Upvotes: 3

Related Questions