2

我有一个这样的伴生对象:

object Addresses extends Table[Address]("address"){
  //some mapping columns
  .... 

  //a method I want to made generic 
  def findAll(limit: Option[Int], offset: Option[Int]): Seq[Address] = DBTest.db.withSession { implicit db: Session =>
    (limit, offset) match {
      case (Some(l), Some(o)) => Addresses.map { a => a }.drop(o).take(l).list
      case (None, None) => Addresses.map { a => a }.drop(ConfigurationsLoader.DefaultOffset).take(ConfigurationsLoader.DefaultLimit).list
      case (Some(l), None) => Addresses.map { a => a }.take(l).list
      case (None, Some(o)) => Addresses.map { a => a }.drop(o).list
    }
  }

案例类Address

因为我有很多这样的对象(每个都定义一个表),所以我想findAll在一个 trait 中移动方法,使其具有通用性,我试图这样做:

trait DbGenericOperations[T, U <: Table[T]]{
  val entities: U
  /**
   * Based on REST conventions, for listing it's good to use limit and offset, like: /entities?limit=25&offset=50.
   */
  def findAll(limit: Option[Int], offset: Option[Int]): Seq[T] = DBTest.db.withSession { implicit db: Session =>
    (limit, offset) match {
      case (Some(l), Some(o)) => entities.map { a => a }.drop(o).take(l).list
      case (None, None) => entities.map { a => a }.drop(ConfigurationsLoader.DefaultOffset).take(ConfigurationsLoader.DefaultLimit).list
      case (Some(l), None) => entities.map { a => a }.take(l).list
      case (None, Some(o)) => entities.map { a => a }.drop(o).list
    }
  }
}

如您所见,entities它基本上是我的伴侣对象。

现在的问题是我不能像这样重写我的对象定义:

object Addresses extends Table[Address]("address") with DbGenericOperations[Address, Addresses]{

因为它说那Addresses不是一种类型......

我对 scala 很陌生,我想知道:有没有办法解决这个问题?

更新:我已经这样做了:

trait DbGenericOperations[T]{
      /**
       * Based on REST conventions, for listing it's good to use limit and offset, like: /entities?limit=25&offset=50.
       */
      def findAll(limit: Option[Int], offset: Option[Int], entities: Table[T]): Seq[T] = DBTest.db.withSession { implicit db: Session =>
        (limit, offset) match {
          case (Some(l), Some(o)) => entities.map { a => a }.drop(o).take(l).list
          case (None, None) => entities.map { a => a }.drop(ConfigurationsLoader.DefaultOffset).take(ConfigurationsLoader.DefaultLimit).list
          case (Some(l), None) => entities.map { a => a }.take(l).list
          case (None, Some(o)) => entities.map { a => a }.drop(o).list
        }
      }
    }

并像这样声明伴随对象: object Addresses extends Table[Address]("address") with DbGenericOperations[Address]

但我不喜欢使用这种方法:

val results = Addresses.findAll(limit, offset, Addresses)

请让我知道是否有更好的解决方案...

4

1 回答 1

1

为什么不创建一个类/特征 RichTable[T](...) extends Table[T](...) 来添加这个方法?

于 2012-11-27T23:30:48.620 回答