mapped projection with companion object in SLICK

前端 未结 1 1178
死守一世寂寞
死守一世寂寞 2020-12-05 01:37

I have nested classes/objects and want to store (and retrieve) them in a database by using SLICK. I understand that with SLICK mapped projection would be key. Furthermore I

相关标签:
1条回答
  • 2020-12-05 01:49

    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 _)
    
    0 讨论(0)
提交回复
热议问题