hanno tali modelli (semplificato):Scala inferenza di tipo, lavorando con tavolo Slick
case class User(id:Int,name:String)
case class Address(id:Int,name:String)
...
Slick (2.1.0 versione) tabella di mapping:
class Users(_tableTag: Tag) extends Table[User](_tableTag, "users") with WithId[Users, User] {`
val id: Column[Int] = column[Int]("id", O.AutoInc, O.PrimaryKey)
...
}
trait WithId[T, R] {
this: Table[R] =>
def id: Column[Int]
}
miscelazione tratto WithId
Voglio realizzare DAO generico metodi per diverse tabelle con colonna id: Column[Int]
(Voglio metodo findById
per lavorare con entrambe le associazioni di tabelle User
e Address
)
trait GenericSlickDAO[T <: WithId[T, R], R] {
def db: Database
def findById(id: Int)(implicit stk: SlickTableQuery[T]): Option[R] = db.withSession { implicit session =>
stk.tableQuery.filter(_.id === id).list.headOption
}
trait SlickTableQuery[T] {
def tableQuery: TableQuery[T]
}
object SlickTableQuery {
implicit val usersQ = new SlickTableQuery[Users] {
val tableQuery: Table Query[Users] = Users
}
}
Il problema è che findById
non compila:
Error:(13, 45) type mismatch; found : Option[T#TableElementType] required: Option[R] stk.tableQuery.filter(_.id === id).list.headOption
come la vedo io T
è di tipo WithId[T, R]
e al tempo stesso è di tipo Table[R]
. Slick implementa il tipo Table
tale che se X=Table[Y]
quindi X#TableElementType=Y
.
Quindi nel mio caso T#TableElementType=R
e Option[T#TableElementType]
devono essere dedotti come Option[R]
ma non lo è. Dove mi sbaglio?
grazie mille per questa soluzione! – ka4eli