我正在使用Scala和doobie开展项目。我试图实现一个可以由MacWire注入并与不同的任务/未来单子一起使用的交易者特征(例如用于测试)。
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]
,但是将IOLite
定义为IOLite[A]
。我能以任何方式使这项工作?或者我 使用不同的Monad类型而不是Task
(doobie测试需要更改IOLite
)?
答案 0 :(得分:2)
试试:
override val transactor = doobie.h2.imports.H2Transactor[M](...).widen
如果widen
有cats
个实例, scalaz
是一个可用的操作(M
和Functor
)。如果M[A]
是M[B]
A
视为B