gpt4 book ai didi

scala - 将泛型定义为案例类

转载 作者:行者123 更新时间:2023-12-02 18:21:31 25 4
gpt4 key购买 nike

在这个例子中,我希望通用 T 是一个 case class 和一个 DAOEntity with id ,所以在抽象实现中,我可以使用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 同伴) 都没有扩展。这是有道理的,这种函数的类型签名是什么?

你可以做的是创建一个类似工厂的 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 .

关于scala - 将泛型定义为案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70814434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com