Scala (doobie):类型是不变的

Scala (doobie): Type is invariant

我正在使用 Scala 和 doobie. I'm trying to implement a transactor trait that may be injected by MacWire 开发一个项目,并使用不同的 Task/Future monad(例如用于测试)。

import doobie.imports
import doobie.imports._
import fs2.Task
import fs2.util.{Catchable, Suspendable}

trait Transactor[M[_]] {
  implicit def catchable: Catchable[M] = implicitly
  val transactor: M[imports.Transactor[M]]
  def transact[A](q: ConnectionIO[A]): M[A] = catchable.flatMap(transactor)(xa => q.transact(xa))
}

case class H2Transactor[M[_]: Catchable: Suspendable](pure: PureConfig) extends Transactor[M] {
  override val transactor = doobie.h2.imports.H2Transactor[M](
    pure.config.persistence.name,
    pure.config.persistence.user.orNull,
    pure.config.persistence.password.orNull
  )
}

...
trait DatabaseModule { lazy val transactor = wire[H2Transactor[Task]] }
trait TestModule { lazy val transactor = wire[H2Transactor[IOLite]] }

但是我得到这个错误:

[error] .../src/main/scala/.../persistence/transactor/H2Transactor.scala:13: type mismatch;
[error]  found   : M[doobie.h2.h2transactor.H2Transactor[M]]
[error]  required: M[doobie.imports.Transactor[M]]
[error]     (which expands to)  M[doobie.util.transactor.Transactor[M]]
[error] Note: doobie.h2.h2transactor.H2Transactor[M] <: doobie.imports.Transactor[M], but type M is invariant in type _.
[error] You may wish to define _ as +_ instead. (SLS 4.5)

它适用于 Task,因为它被定义为 Task[+A],但 doobie 的 IOLite 被定义为 IOLite[A]。我有什么办法可以使这项工作?或者我 使用不同的 Monad 类型而不是 Task (不能更改 IOLite 是 doobie 测试所必需的)?

试试看:

override val transactor = doobie.h2.imports.H2Transactor[M](...).widen
如果 M 有一个 Functor 实例,

widen 是一个可用的操作(在 catsscalaz 中)。如果 AB

的子类,它允许您将 M[A] 视为 M[B]