4

我正在玩 slick 3.0.0 的新 DBIO api,但在泛型方面遇到了一些问题。

使用此代码:

import scala.concurrent._

import slick.driver.MySQLDriver.api._
import slick.lifted.AbstractTable

object Crud {

  def fetchById[T: AbstractTable[R], R](db: Database, table: TableQuery[T], id: Int, rowId: T => Rep[Int]): Future[Option[T]] = {
    val fetchByIdQuery: Query[T, R, Seq] = table.filter(row => rowId(row) === id)

    db.run(fetchByIdQuery.result)
  }
}

编译器说 AbstractTable 不接受任何类型参数。我不理解这里看到的声明https://github.com/slick/slick/blob/3.0/slick/src/main/scala/slick/lifted/AbstractTable.scala

slick.lifted.AbstractTable[R] does not take type parameters
def fetchById[T: AbstractTable[R], R](db: Database, table: TableQuery[T], id: Int, rowId: T => Rep[Int]): Future[Option[T]] = {

我怀疑这也是导致此错误的原因。

type mismatch;
 found   : slick.lifted.Query[T,T#TableElementType,Seq]
 required: slick.driver.MySQLDriver.api.Query[T,R,Seq]
    (which expands to)  slick.lifted.Query[T,R,Seq]
    val fetchByIdQuery: Query[T, R, Seq] = table.filter(row => rowId(row) === id)

有什么建议吗?

4

1 回答 1

1

试试这个方法

T <: AbstractTable[R]  // instead of T : AbstractTable[R]

所以它应该如下所示

Object Crud {
def fetchById[T <: AbstractTable[R], R](db: Database, table: TableQuery[T], id: Int, rowId: T => Rep[Int])
 : Future[Option[T#TableElementType]] =  {
  val fetchByIdQuery = table.filter(row => rowId(row) === id)
  db.run(fetchByIdQuery.result.headOption)
 }
}
于 2015-06-11T20:00:41.930 回答