복붙노트

[SCALA] 스칼라는 : 어떻게 어떤 경우 클래스의 추상 복사 가능한 슈퍼 클래스를 정의?

SCALA

스칼라는 : 어떻게 어떤 경우 클래스의 추상 복사 가능한 슈퍼 클래스를 정의?

영업 이익은 의미가 될 때까지 나와 함께 곰하시기 바랍니다, 어떤 상황이있다. 나는 슬릭의 3.1.X와 매끄러운 코드 생성기를 사용하고 있습니다. BTW 전체 소스 코드는 플레이 인증합니다 - 사용 - 스칼라 GitHub의 프로젝트에서 찾을 수 있습니다. 이 프로젝트를 위해 나는 모든 모델에 대해 동일한 상용구 코드를 반복하지 않도록하는 매끄러운 일반적인 다오을 가지고 싶습니다.

여기 진화를 사용하여 데이터베이스를 생성하는 포스트 그레스 SQL 스크립트가 : 1.sql

나는 다음 데이터 모델을 생성하는 발전기를 호출 : Tables.scala

나는 그들에게 예를 들어, 몇 가지 기본적인 추상화을 준수하는 데 필요한 모델 클래스에 대한 일반적인 DAO의 매끄러운 구현을 제공 할 수 있어야합니다

이 copyWithNewId은 영업 이익의 포인트입니다. 이 copyWithNewId 호출되지 않고 있음을 참고 무한 재귀를 방지하기 위해 복사합니다. 삽입하는 즉시 자동으로 생성 된 ID를 인출 허용 GenericDaoAutoIncImpl을 구현할 수 있도록, 엔티티 행 사본 (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)
}

그러나 내가 할 수있는 경우 - 일부 스칼라 트릭을 사용하여 - 내 <모델> 행의 경우 클래스를 서브 클래스 복사 가능한 및 전달 idi.e.을 제외하고 자신을 복사하는 기본 클래스의 정의 IdCopyable 그때를 통해 구현하고 모든 <모델> 행 생성 된 경우 클래스에 대한이 copyWithNewId 이상 필요하지 않을 사본 (ID = ID)와.

에 방법이 있나요 추상적 인 또는 id 속성이 포함되어있는 경우 클래스에 리팩터링 사본 (ID = ID)를 "끌어"? 다른 권장 솔루션이있다?

UPDATE 한 다음 거의 내가 가지고있는 문제를 요약 한 것입니다 :

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

UPDATE 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]                                                                ^

해결법

  1. ==============================

    1.볼품하면 추상적 인 이상의 경우 클래스를 할 수 있습니다.

    볼품하면 추상적 인 이상의 경우 클래스를 할 수 있습니다.

    당신은 모든 ID가 긴 케이스 클래스의 첫 번째 매개 변수라고 가정하면, 다음과 같습니다

    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 항을 참조하십시오.

    당신은 재사용 typeclass이 로직을 캡슐화 할 수 있습니다 :

    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)
    

    중요한 것은 당신이이 상황에 맞는 범위 또는 암시 적 매개 변수의 사용을 통해, 필요한 곳에 사용 사이트에서 typeclass 인스턴스를 전달한다는 것입니다.

    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)))
    }
    

    볼품은 정확히이 목적을 위해 사용할 수있는 렌즈를 제공합니다. 그런 식으로 당신은 어떤 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))
    

    typeclass IdCopy [A, ID]의 인스턴스 암시 파라미터로서 요청 방법도 copyWithId 사용되는 방법 assignNewIds에서 공지. copyWithId 그것이 사용될 때 범위에있을 IdCopy [A, ID] 내재적 인스턴스를 필요로하기 때문이다. 당신은 당신이 그런 푸 등의 구체적인 유형, copyWithId가 호출되는 경우에 호출 체인 끝까지 작업을 사용하는 사이트에서 암시 적 인스턴스를 전달해야합니다.

    당신은 방법의 종속성으로 암시 적 매개 변수를 볼 수 있습니다. 방법 유형 IdCopy [A, ID] 내재적 변수가있는 경우에는이를 호출 할 때 그 종속성을 충족 할 필요가있다. 종종 그 또한 둔다는 호출되는 곳에서 방법에 같은 의존성이.

  2. from https://stackoverflow.com/questions/40995639/scala-how-to-define-an-abstract-copyable-superclass-for-any-case-class by cc-by-sa and MIT license