0

I need to abstract the copy method generated by Scala compiler for case classes with its parameters. In my case, I have a save method like below

def save[T<:Data](data:T):T={
// store in db and get the id
  val dbId = ...
  data.copy(dbId)
}

and a set of case classes like below

trait Data
case class Foo (id:Option[Int] = None,name:String,age:Int) extends Data
case class Bar (id:Option[Int] = None, name:String,address:String) extends Data

How can I abstract the copy method, any alternative solution would be appreciated.

Ali Salehi
  • 6,899
  • 11
  • 49
  • 75
  • You can do this with macros in Scala 2.10—see for example my answer [here](http://stackoverflow.com/a/13447439/334519). – Travis Brown Oct 17 '13 at 13:14
  • The generated `copy` method has no parameters, please clarify. – Chirlo Oct 17 '13 at 13:18
  • You can introduce a trait that has id and then make a save method for this trait, and extend your table representations with it. – Ashalynd Oct 17 '13 at 13:26
  • Actually, the case-class `copy` method has exactly the same parameters as the construct, it's just that they're all optional. Any that *are* supplied are used to make the copy different from the original (otherwise there's little reason to copy an immutable value...). – Randall Schulz Oct 17 '13 at 19:32

0 Answers0