简体   繁体   中英

Scala`s <> operator meaning

I am trying to learn Scala in order to use it with Play Framework. Now I am dealing with Play for Scala + Slick for database layer and I am using a piece of code from tutorial which I do not understand and I am unable to find any info in Scala manual.

Here is the thing. I have got model named Entry. It is defined as case class and I have a companion class extended from Table.

case class Entry(id: Int, name: String)

class EntryTable(tag: Tag) extends Table[Entry](tag, "entries") {
  def id = column[Int]("id", O.PrimaryKey)
  def name = column[String]("name")
  def * = (id, name) <> (Entry.tupled, Entry.unapply(_))
}

What I do not understand, is the last line with def * . I know, that it has something to do with reflection. Basically I would understand the part def * = (id, name) , but what does mean the other part. I cannot find meaning of operator <> ? Can anyone explain this to me?

The operator <> means a projection between the tuple (Int, String) and case class Entry .

It can be explained in steps:

  1. In order to return objects, Slick needs a * projection ( * is from SELECT * in SQL)
  2. This projection can be defined in various ways, but the most common is using <> operator. It's signature, when simplified, looks like: <>[T, C](apply: T => C, unapply: C => Option[T])
  3. (id, name) constructs a tuple of (Int, String) (simplified, actually it's (Rep[Int], Rep[String]) , but Slick will unlift it later)
  4. <> maps it to Entry , because Entry has apply with signature (Int, String) => Entry , which is transformed by .tupled to ((Int, String)) => Entry , and unapply with signature Entry => Option[(Int, String)] .
  5. Now you have * projection that can construct Entry objects from database rows and rows from objects.

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