Scala (doobie): Type is invariant

283 views Asked by At

I'm working on a project with Scala and doobie. I'm trying to implement a transactor trait that may be injected by MacWire and used with different Task/Future monads (e.g. for tests).

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]] }

But I get this error:

[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)

It works for Task because it is defined as Task[+A], but doobie's IOLite as IOLite[A]. Any way I can make this work? Or do I have to use a differnt Monad type instead of Task (can't change IOLite is required for doobie tests)?

1

There are 1 answers

1
Oleg Pyzhcov On BEST ANSWER

Try that:

override val transactor = doobie.h2.imports.H2Transactor[M](...).widen

widen is an operation that is available (in both cats and scalaz) if M has a Functor instance. It allows you to treat M[A] as M[B] if A is a subclass of B