1

I have case class with a lot of fields

 case class H(     
                           id: Int, 
                           min: Option[String] = None,
                           max: Option[String] = None,
                           step: Option[String] = None,
                           ...
                           ) 

How can I map a few field to the table?

class TH(tag: Tag) extends Table[H](tag, "H") {
  def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
  def min = column[Option[String]]("M")

  def * = (id, min) <>(H.tupled, H.unapply)
}

when I tried like this - def * = (id, min) <>(H.tupled, H.unapply) , instead of map all fields, got compilation exception. Can I map custom field to the table ?

BR!

initmax
  • 395
  • 2
  • 10

1 Answers1

2

tupled and unapply are just basics function generated by the case class which define the following functions (among other things) with all the fields of the case class.

For example, for a case class X(a: A, b: B, c: C, d: D), you have:

def tupled(a: a, b: b, c: c, d: d): X
def unapply(x: X): Option[(A, B, C, D)]

In other hand, your projection constructed with <> expects parameters: (f: (U => R), g: (R => Option[U])), where U is the combinaison of your fields type.

You're not tied to use the "automatic" tupled/unapply if they don't match your needs, you can provides your own definition:

class TH(tag: Tag) extends Table[H](tag, "H") {
  def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
  def min = column[Option[String]]("M")

  def * = (id, min) <> (
    { tuple: (Long, Option[String]) => TH(id, min) },
    { th: TH => Some((th.id, th.min)) }
  )
}
Julien Lafont
  • 7,869
  • 2
  • 32
  • 52