简体   繁体   中英

What is 'override def *' in Scala Slick schema trait

case class Fruit(
                     apple: String,
                     banana: String
                   )


trait AppleComponent { self: HasDatabaseConfig[JdbcProfile] =>
  import profile.api._

  class Fruits(tag: Tag) extends Table[Fruit](tag, "fruits") {
    def apple      = column[String]("apple")
    def banana     = column[String]("banana")
    // what is this line of code used for?
    override def *    = (apple,banana) <> (Fruit.tupled, Fruit.unapply)
    def applePK = primaryKey("apple", apple)
  }

  protected lazy val Apples = TableQuery[Fruits]

}

I am new to Scala Slick ,so I want to know what does override def * = (apple,banana) <> (Fruit.tupled, Fruit.unapply) mean? I really can't find any document about it. Also, why we need a trait here?

Table class has * method which should implements SELECT * FROM ... semantics. Since Slick cannot guess how you want to extract columns, you have to write this manually (using all columns in the order you want).

<> is just so that you will have a case class returned by * rather than a tuple.

You don't need trait here. This:

// module name
trait AppleComponent {
  // self-type for dependency injection
  self: HasDatabaseConfig[JdbcProfile] =>

  // dependencies injected by mixing-in this trait:

  protected lazy val Apples = TableQuery[Fruits]
}

is called a cake pattern. In general it is an anti-pattern (but ZIO promotes recently a specific way of using it).

I'd say whatever documentation or tutorial you are using is outdated by a few years.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM