【问题标题】:Scala: how to define an abstract copyable superclass for any case class?Scala:如何为任何案例类定义一个抽象的可复制超类?
【发布时间】:2017-04-21 02:36:07
【问题描述】:

请耐心等待,在 OP 有意义之前有一些上下文。我正在使用 Slick 3.1.x 和 slick 代码生成器。顺便说一句,整个源代码可以在play-authenticate-usage-scala github project 中找到。对于这个项目,我希望有一个灵活的通用 Dao,以避免为每个模型重复相同的样板代码。

我有一个 postgres sql 脚本,它在这里使用进化创建数据库: 1.sql

然后我调用生成以下数据模型的生成器: Tables.scala

为了能够为模型类提供通用的 dao slick 实现,我需要它们遵守一些基本抽象,例如

  • Entity 特征:每个实体都有一个 id,例如需要dao的findById
  • AutoIncEntity trait 声明了方法 def copyWithNewId(id : PK) : Entity[PK]。这对于 dao 的 createAndFetch 实现是必需的,它持久化一个新实体并在一步中检索自动生成的 id PK。

这个copyWithNewId 是 OP 的重点。请注意,它被称为copyWithNewId 而不是copy 以避免无限递归。为了能够实现允许插入和立即获取自动生成的idGenericDaoAutoIncImpl,实体行需要来自<Model>Row 案例类的copy(id = id) 方法,该方法在定义GenericDaoAutoIncImpl 时目前还不知道。相关实现如下:

override def createAndFetch(entity: E): Future[Option[E]] = {
  val insertQuery = tableQuery returning tableQuery.map(_.id) 
                        into ((row, id) => row.copyWithNewId(id))
  db.run((insertQuery += entity).flatMap(row => findById(row.id)))
}

这需要我在每个 AutoInc id 生成的模型中实现 copyWithNewId 方法,这并不好,例如

// generated code and modified later to adapt it for the generic dao 
case class UserRow(id: Long, ...) extends AutoIncEntity[Long] with Subject {
  override def copyWithNewId(id : Long) : Entity[Long] = this.copy(id = id)
}

但是,如果我可以 - 使用一些 Scala 技巧 - 定义我的 <Model>Row 案例类子类,该子类是可复制的,并且除了传递的 idi.e 之外,它会复制自身。 IdCopyablecopy(id = id) 那么我不需要为每个<Model>Row 生成的案例类一遍又一遍地实现这个copyWithNewId

对于任何包含id 属性的案例类,有没有办法抽象或“拉起”重构copy(id = id)?还有其他推荐的解决方案吗?

更新 1 以下内容大致概括了我遇到的问题:

scala> abstract class BaseA[A <: BaseA[_]] { def copy(id : Int) : A }
defined class BaseA

scala> case class A(id: Int) extends BaseA[A]
<console>:12: error: class A needs to be abstract, since method copy in class BaseA of type (id: Int)A is not defined
   case class A(id: Int) extends BaseA[A]
              ^

scala> case class A(id: Int); val a = A(5); a.copy(6)
defined class A
a: A = A(5)
res0: A = A(6)

更新 2 使用下面建议的解决方案,我得到以下编译错误:

[error] /home/bravegag/code/play-authenticate-usage-scala/app/dao/GenericDaoAutoIncImpl.scala:26: could not find implicit value for parameter gen: shapeless.Generic.Aux[E,Repr]
[error]     val insertQuery = tableQuery returning tableQuery.map(_.id) into ((row, id) => row.copyWithNewId(id))
[error]                                                                                                     ^
[error] /home/bravegag/code/play-authenticate-usage-scala/app/dao/GenericDaoAutoIncImpl.scala:27: value id is not a member of insertQuery.SingleInsertResult
[error]     db.run((insertQuery += entity).flatMap(row => findById(row.id)))
[error]                                                                ^
[error] two errors found

更新 3 使用和调整以下建议的镜头解决方案我收到以下编译器错误:

import shapeless._, tag.@@
import shapeless._
import tag.$at$at

/**
  * Identifyable base for all Strong Entity Model types
  * @tparam PK Primary key type
  * @tparam E Actual case class EntityRow type
  */
trait AutoIncEntity[PK, E <: AutoIncEntity[PK, E]] extends Entity[PK] { self: E =>
  //------------------------------------------------------------------------
  // public
  //------------------------------------------------------------------------
  /**
    * Returns the entity with updated id as generated by the database
    * @param id The entity id
    * @return the entity with updated id as generated by the database
    */
  def copyWithNewId(id : PK)(implicit mkLens: MkFieldLens.Aux[E, Symbol @@ Witness.`"id"`.T, PK]) : E = {
    (lens[E] >> 'id).set(self)(id)
  }
}

然后我得到以下编译器错误:

[error] /home/bravegag/code/play-authenticate-usage-scala/app/dao/GenericDaoAutoIncImpl.scala:26: could not find implicit value for parameter mkLens: shapeless.MkFieldLens.Aux[E,shapeless.tag.@@[Symbol,String("id")],PK]
[error]     val insertQuery = tableQuery returning tableQuery.map(_.id) into ((row, id) => row.copyWithNewId(id))
[error]                                                                                                     ^
[error] /home/bravegag/code/play-authenticate-usage-scala/app/dao/GenericDaoAutoIncImpl.scala:27: value id is not a member of insertQuery.SingleInsertResult
[error]     db.run((insertQuery += entity).flatMap(row => findById(row.id)))
[error]                                                                ^

【问题讨论】:

    标签: scala slick


    【解决方案1】:

    使用shapeless,您可以抽象案例类。

    1。手动抽象案例类

    如果您假设每个id 都是Long 并且是案例类的第一个参数,它可能如下所示:

    scala> import shapeless._, ops.hlist.{IsHCons, Prepend}
    import shapeless._
    import ops.hlist.{IsHCons, Prepend}
    
    scala> trait Copy[A <: Copy[A]] { self: A =>
         |   def copyWithId[Repr <: HList, Tail <: HList](l: Long)(
         |     implicit 
         |     gen: Generic.Aux[A,Repr], 
         |     cons: IsHCons.Aux[Repr,Long,Tail], 
         |     prep: Prepend.Aux[Long :: HNil,Tail,Repr]
         |   ) = gen.from(prep(l :: HNil, cons.tail(gen.to(self))))
         | }
    defined trait Copy
    
    scala> case class Foo(id: Long, s: String) extends Copy[Foo]
    defined class Foo
    
    scala> Foo(4L, "foo").copyWithId(5L)
    res1: Foo = Foo(5,foo)
    

    也有可能以更清洁的方式;我还不是很精通无形编程。而且我相当确定也可以在参数列表中的任何位置为具有任何类型id 的案例类执行此操作。 见下文第 2 段。


    您可能希望将此逻辑封装在可重用的类型类中:

    scala> :paste
    // Entering paste mode (ctrl-D to finish)
    
    import shapeless._, ops.hlist.{IsHCons, Prepend}
    
    sealed trait IdCopy[A] {
      def copyWithId(self: A, id: Long): A
    }
    
    object IdCopy {
      def apply[A: IdCopy] = implicitly[IdCopy[A]]
      implicit def mkIdCopy[A, Repr <: HList, Tail <: HList](
        implicit 
        gen: Generic.Aux[A,Repr], 
        cons: IsHCons.Aux[Repr,Long,Tail], 
        prep: Prepend.Aux[Long :: HNil,Tail,Repr]
      ): IdCopy[A] = 
        new IdCopy[A] {
          def copyWithId(self: A, id: Long): A = 
            gen.from(prep(id :: HNil, cons.tail(gen.to(self))))
        }
    }
    
    // Exiting paste mode, now interpreting.
    
    import shapeless._
    import ops.hlist.{IsHCons, Prepend}
    defined trait IdCopy
    defined object IdCopy
    
    scala> def copy[A: IdCopy](a: A, id: Long) = IdCopy[A].copyWithId(a, id)
    copy: [A](a: A, id: Long)(implicit evidence$1: IdCopy[A])A
    
    scala> case class Foo(id: Long, str: String)
    defined class Foo
    
    scala> copy(Foo(4L, "foo"), 5L)
    res0: Foo = Foo(5,foo)
    

    如果这对您很重要,您仍然可以将您的 copyWithId 方法放入您的案例类可以扩展的特征中:

    scala> trait Copy[A <: Copy[A]] { self: A =>
         |   def copyWithId(id: Long)(implicit copy: IdCopy[A]) = copy.copyWithId(self, id)
         | }
    defined trait Copy
    
    scala> case class Foo(id: Long, str: String) extends Copy[Foo]
    defined class Foo
    
    scala> Foo(4L, "foo").copyWithId(5L)
    res1: Foo = Foo(5,foo)
    

    重要的是通过使用上下文边界或隐式参数将类型类实例从使用站点传播到需要它的位置。

    override def createAndFetch(entity: E)(implicit copy: IdCopy[E]): Future[Option[E]] = {
      val insertQuery = tableQuery returning tableQuery.map(_.id) 
                            into ((row, id) => row.copyWithId(id))
      db.run((insertQuery += entity).flatMap(row => findById(row.id)))
    }
    

    2。使用镜头

    Shapeless 还提供了lenses,您可以将其用于此目的。这样,您就可以更新任何具有 id 字段的案例类的 id 字段。

    scala> :paste
    // Entering paste mode (ctrl-D to finish)
    
    sealed trait IdCopy[A,ID] {
      def copyWithId(self: A, id: ID): A
    }
    
    object IdCopy {
      import shapeless._, tag.@@
      implicit def mkIdCopy[A, ID](
        implicit 
        mkLens: MkFieldLens.Aux[A, Symbol @@ Witness.`"id"`.T, ID]
      ): IdCopy[A,ID] = 
        new IdCopy[A,ID] {
          def copyWithId(self: A, id: ID): A = 
            (lens[A] >> 'id).set(self)(id)
        }
    }
    
    
    def copyWithId[ID, A](a: A, elem: ID)(implicit copy: IdCopy[A,ID]) = copy.copyWithId(a, elem)
    
    // Exiting paste mode, now interpreting.
    
    defined trait IdCopy
    defined object IdCopy
    copyWithId: [ID, A](a: A, elem: ID)(implicit copy: IdCopy[A,ID])A
    
    scala> trait Entity[ID] { def id: ID }
    defined trait Entity
    
    scala> case class Foo(id: String) extends Entity[String]
    defined class Foo
    
    scala> def assignNewIds[ID, A <: Entity[ID]](entities: List[A], ids: List[ID])(implicit copy: IdCopy[A,ID]): List[A] =
         |   entities.zip(ids).map{ case (entity, id) =>  copyWithId(entity, id) }
    assignNewIds: [ID, A <: Entity[ID]](entities: List[A], ids: List[ID])(implicit copy: IdCopy[A,ID])List[A]
    
    scala> assignNewIds( List(Foo("foo"),Foo("bar")), List("new1", "new2"))
    res0: List[Foo] = List(Foo(new1), Foo(new2))
    

    请注意,在使用copyWithId 的方法assignNewIds 中,类型类IdCopy[A,ID] 的实例作为隐式参数被请求。这是因为copyWithId 在使用时需要IdCopy[A,ID] 的隐式实例在范围内。您需要从使用具体类型(例如Foo)的使用站点传播隐式实例,一直沿调用链向下到调用copyWithId 的位置。

    您可以将隐式参数视为方法的依赖项。如果方法具有IdCopy[A,ID] 类型的隐式参数,则在调用它时需要满足该依赖关系。通常这也会对调用它的方法产生同样的依赖。

    【讨论】:

    • 谢谢!!如果它有效,我很高兴,但是......这个特征的代码很糟糕:D
    • 我想过,但 typeclass 最后会创建包装器,这可能会成为数据驱动的 Web 应用程序的性能缺陷。模型包装器实例从 dao 出站是可以的,但不确定它们何时进入 DAO。
    • 我收到编译器错误could not find implicit value for parameter gen: shapeless.Generic.Aux[E,Repr] 看到更新的问题。
    • @GiovanniAzua 这就是为什么它是评论,而不是答案。
    猜你喜欢
    • 2016-04-13
    • 2011-06-16
    • 2019-08-26
    • 1970-01-01
    • 2018-03-25
    • 2015-10-23
    • 1970-01-01
    • 2018-02-17
    • 2012-10-18
    相关资源
    最近更新 更多