Instead of unapply
and apply
, you could just pass in lambdas that do what you want:
def * = id ~ myInt ~ myString <> (
(id,myInt,myString) => Foo(id, Bar(myInt, myString)), /* from a row to a Foo */
(f:Foo) => Some((f.id, f.myBar.myInt, f.myBar.myString)) /* and back */)
This way, the mapping from table rows to case classes stays in the table definition, and the case classes stay as simple case classes, which isn't too bad.
The other way would have been to not use a case class for Foo
, but a regular class instead which leaves you free to define your own apply
and unapply
in a companion object, like so:
// untested code
class Foo private (val id: Int, val myBar: Bar)
case class Bar(myInt: Int, myString: String)
object Foo {
def apply(id: Int, myInt: Int, myString: String): Foo = new Foo(id, Bar(myInt, myString))
def unapply(f: Foo) = Some((f.id, f.myBar.myInt, f.myBar.myString))
}
If you want to do def * = id ~ myInt ~ myString <> (Foo.apply _, Foo.unapply _)
You'll get case-class-like usage to an extent, but you might miss the other nice stuff
like having equals
and toString
for free as with actual case classes.
I'd rather keep the case classes (and their default apply
unapply
) so they can be treated as algebraic data types in the normal convention.
The real issue here is that case classes have their own unapply
so you can't (as far as I know) have a similar method (same name and same arguments) in your companion class.
You could simply just use another method name. After all, what you want to do isn't
semantically equivalent to unapply
anyway:
object Foo {
def fromRow(id: Int, myInt: Int, myString: String): Foo = Foo(id, Bar(myInt, myString))
def toRow(f: Foo) = Some((f.id, f.myBar.myInt, f.myBar.myString))
}
Then in your table schema:
def * = id ~ myInt ~ myString <> (Foo.fromRow _, Foo.toRow _)