Suppose these two simple queries are:
def findById(id: Long): Option[Account] = database.withSession { implicit s: Session => val query = for (a <- Accounts if a.id === id) yield a.* query.list.headOption } def findByUID(uid: String): Option[Account] = database.withSession { implicit s: Session => val query = for (a <- Accounts if a.uid === uid) yield a.* query.list.headOption }
I would like to rewrite it to remove duplicate patterns like this:
def findBy(criteria: ??? => Boolean): Option[Account] = database.withSession { implicit s: Session => val query = for (a <- Accounts if criteria(a)) yield a.* query.list.headOption } def findById(id: Long) = findBy(_.id === id) def findByUID(uid: Long) = findBy(_.uid === uid)
I do not know how to achieve it, because there are several implicit transformations for understanding that I have not yet untangled. More specifically: what type ??? => Boolean ??? => Boolean in findBy method?
EDIT
These are the classes of accounts and accounts:
case class Account(id: Option[Long], uid: String, nick: String) object Accounts extends Table[Account]("account") { def id = column[Option[Long]]("id") def uid = column[String]("uid") def nick = column[String]("nick") def * = id.? ~ uid ~ nick <> (Account, Account.unapply _) }
source share