将泛型定义为案例 class

Defining a generic to be a case class

在这个例子中,我希望泛型 T 是一个 case class 和一个 DAOEntityid,所以在抽象实现中,我可以使用copy 方法。

如何定义?

trait DAOEntity {
  def id: String
}

// How to define this generic to force the use of a `case class` to have access to `copy`?
abstract class DAO[T <: DAOEntity] {
  def storeInUppercase(entity: T): T = entity.copy(id = entity.id)
}

case class MyEntity(id: String) extends DAOEntity

class MyEntityDAO extends DAO[MyEntity] {
  // Other stuff
}

无法知道类型是否为 case class
即使有,您也不会获得 copy 方法。该语言不提供对构造函数进行抽象的方法;因此 copy 和工厂 (同伴上的 apply 都没有。这是有道理的,这种函数的类型签名是什么?

你可以做的是创建一个 factory-like typeclass 并要求它:

trait DAOFactory[T <: DAOEntity] {
  def copy(oldEntity: T, newId: String): T
}
object DAOFactory {
  def instance[T <: DAOEntity](f: (T, String) => T): DAOFactory[T] =
    new DAOFactory[T] {
      override final def copy(oldEntity: T, newId: String): T =
        f(oldEntity, newId)
    }
}

可以这样使用:

abstract class DAO[T <: DAOEntity](implicit factory: DAOFactory[T]) {
  def storeInUppercase(entity: T): T =
    factory.copy(
      oldEntity = entity,
      newId = entity.id.toUpperCase
    )
}

实体将提供这样的实例:

final case class MyEntity(id: String, age: Int) extends DAOEntity
object MyEntity {
  implicit final val MyEntityFactory: DAOFactory[MyEntity] =
    DAOFactory.instance {
      case (oldEntity, newId) =>
        oldEntity.copy(id = newId)
    }
}

// This compile thanks to the instance in the companion object.
object MyEntityDAO extends DAO[MyEntity]

可以看到代码运行 here.