Scala编译器推断通用参数没有任何内容

时间:2014-09-20 15:00:02

标签: scala generics implicit-conversion type-inference slick

我正在尝试以前在不同环境中以不同形状看到过的东西: 使用filterById(id: Id)

扩展scala的查询扩展名

这是我尝试过的:

trait TableWithId { self: Profile =>

    import profile.simple._

    trait HasId[Id] { self: Table[_] =>
      def id: Column[Id]
    }

    implicit class HasIdQueryExt[Id: BaseColumnType, U]
    (query: Query[Table[U] with HasId[Id], U]) {
      def filterById(id: Id)(implicit s: Session) = query.filter(_.id === id)
      def insertReturnId(m: U)(implicit s: Session): Id = query.returning(query.map(_.id)) += m
    }
}

这很好,没有真正的魔法。但是因为Table类型没有类型约束,所以我应用filterById的任何查询都会失去它的特异性(现在是通用的Table with HasId[Id]),而我无法再访问它的列({{1除外)当然)。

我不知道如何键入此隐式转换,以防止这种情况发生。可能吗?以下“naieve”解决方案不起作用,因为Scala现在为Id类型推断Nothing:

_.id

我发现突然将Id类型推断为Nothing有点奇怪。我如何提示编译器在哪里查找该Id类型?

1 个答案:

答案 0 :(得分:0)

这是我解决类似问题的方法。我确实使用了特定类型的id。:

trait GenericComponent { this: Profile =>
  import profile.simple._

  abstract class TableWithId[A](tag:Tag, name:String) extends Table[A](tag:Tag, name) {
    def id = column[Option[UUID]]("id", O.PrimaryKey)
  }

  abstract class genericTable[T <: Table[A] , A] {
    val table: TableQuery[T]

    /**
     * generic methods
     */

    def insert(entry: A)(implicit session:Session): A = session.withTransaction { 
      table += entry
      entry
    }

    def insertAll(entries: List[A])(implicit session:Session) = session.withTransaction { table.insertAll(entries:_*) }

    def all: List[A] = database.withSession { implicit session =>
      table.list.map(_.asInstanceOf[A])
    }
  }

  /**
   * generic queries for any table which has id:Option[UUID]
   */
  abstract class genericTableWithId[T <: TableWithId[A], A <:ObjectWithId ] extends genericTable[T, A] {

    def forIds(ids:List[UUID]): List[A] = database.withSession { implicit session =>
      ids match {
        case Nil => Nil
        case x::xs =>table.filter(_.id inSet(ids)).list.map(_.asInstanceOf[A])
      }
    }

    def forId(id:UUID):Option[A] = database.withSession { implicit session =>table.filter(_.id === id).firstOption }

  }
}

然后是您的具体组成部分:

case class SomeObjectRecord(
  override val id:Option[UUID] = None,
  name:String) extends ObjectWithId(id){
  // your function definitions there
} 

trait SomeObjectComponent extends GenericComponent { this: Profile =>
  import profile.simple._

  class SomeObjects(tag: Tag) extends TableWithId[SomeObjectRecord](tag, "some_objects") {
    def name = column[String]("name", O.NotNull)

    def * = (id, name) <> (SomeObjectRecord.tupled, SomeObjectRecord.unapply)
    def nameIdx = index("u_name", (name), unique = true)
  }

  object someobjects extends genericTableWithId[SomeObjects, SomeObjectRecord] {
    val table = TableQuery[Units]

   // your additional methods there; you get insert and insertAll from the parent    
  }
}