我试图抽象一些可以返回任何类型A
,Option[A]
或Seq[A]
的库API。
到目前为止,我有这样的事情:
type Const[T] = T
sealed abstract class Request[F[_], A]
case class GetOne(id: Int) extends Request[Const, Int]
case class GetMany() extends Request[Seq, String]
然后当我使用它时:
def get[F[_], A](request: Request[F, A]): F[A] = request match {
case GetOne(id) => client.getOne[F[A]](id)
case GetMany() => client.getMany[A]() // error: Seq[A] does not conform to F[A]
}
我理解为什么这不起作用F[_]
不是covariant
Seq[_]
的子类或类似的东西。但是,我仍然不确定如何在能够使用Const[A]
的同时解决问题。我绝望了吗?请帮忙。
答案 0 :(得分:7)
对于这种类型的多态,你可以使用类型类概念
考虑
trait Client {
def getOne[X]: X
def getMany[X]: Seq[X]
}
type Const[T] = T
sealed abstract class Request[F[_], A]
case class GetOne(id: Int) extends Request[Const, Int]
case class GetMany() extends Request[Seq, String]
我们可以定义这样的类型类:
trait HandleRequest[R <: Request[F, A], F[_], A] {
def apply(request: R, client: Client): F[A]
}
并针对所需案例进行实例化:
implicit object handleGetOne extends HandleRequest[GetOne, Const, Int] {
def apply(request: GetOne, client: Client): Int = client.getOne
}
implicit object handleGetMany extends HandleRequest[GetMany, Seq, String] {
def apply(request: GetMany, client: Client): Seq[String] = client.getMany
}
现在您可以按如下方式定义常规功能:
implicit class ClientOps(val client: Client) {
def get[R <: Request[F, A], F[_], A](request: R)(implicit handle: HandleRequest[R, F, A]): F[A] =
handle(request, client)
}
如果您想要概括您的请求类型,例如:
case class GetOne[X](id: Int) extends Request[Const, X]
case class GetMany[X]() extends Request[Seq, X]
您可以将实例重新定义为:
implicit def handleGetOne[X] = new HandleRequest[GetOne[X], Const, X] {
def apply(request: GetOne[X], client: Client): X = client.getOne
}
implicit def handleGetMany[X] = new HandleRequest[GetMany[X], Seq, X] {
def apply(request: GetMany[X], client: Client): Seq[X] = client.getMany
}
答案 1 :(得分:1)
几个月后回到这里,我已经意识到我可以使用path-dependent type
来实现相同的结果,同时更简洁,不需要类型类型模式。
type Const[T] = T
sealed trait Request {
type F[_]
type A
type FA = F[A]
def query(client: Client): Future[FA]
}
case class GetOne(id: Int) extends Request {
type F[x] = Const[x]
type A = Int
def query(client: Client): Future[Int] = client.getOne(id)
}
case class GetMany(id: Int) extends Request {
type F[x] = Seq[x]
type A = String
def query(client: Client): Future[Seq[String]] = client.getMany(id)
}
然后我们可以在没有类型参数爆炸的情况下调用它:
def get[R <: Request](request: R): request.FA = request.query(client)