Search code examples
scalascala-cats

How to use MonadError correctly?


I have the following code, that does not get compiled:

final class DbSystemEnvironment[F[_] : MonadError[F, Throwable]] private(env: Environment[F])
  extends DbSetting[F] {
  override def read(url: String, user: String, pw: String): F[DbParameter] =
    (for {
      a <- OptionT(env.get(url))
      b <- OptionT(env.get(user))
      c <- OptionT(env.get(pw))
    } yield DbParameter(a, b, c))
      .value
      .flatMap {
        case Some(v) => v.pure[F]
        case None => DbSettingError.raiseError[F, DbParameter]
      }

}

The compiler complains:

[error] db/DbSystemEnvironment.scala:10:38: cats.MonadError[F,Throwable] does not take type parameters
[error] final class DbSystemEnvironment[F[_] : MonadError[F, Throwable]] private(env: Environment[F])
[error]                                      ^
[error] db/DbSystemEnvironment.scala:16:9: Could not find an instance of Functor for F
[error]       c <- OptionT(env.get(pw))
[error]         ^
[error] db/DbSystemEnvironment.scala:20:27: value pure is not a member of Any
[error]         case Some(v) => v.pure[F]
[error]                           ^
[error] db/DbSystemEnvironment.scala:21:37: value raiseError is not a member of object io.databaker.db.DbSettingError
[error]         case None => DbSettingError.raiseError[F, DbParameter]

It seems, that I do not use MonadError correctly.

The rest of the code:

final case class DbParameter(url: String, user: String, pw: String)

trait Environment[F[_]] {
  def get(v: String) : F[Option[String]]
}

object Environment {

  def apply[F[_]](implicit ev: Environment[F]): ev.type = ev

  def impl[F[_]: Sync]: Environment[F] = new Environment[F] {
    override def get(v: String): F[Option[String]] =
      Sync[F].delay(sys.env.get(v))
  }
}

How to get the code compiled?


Solution

  • The issue here is the constraint syntax. For a type constructor with a single parameter (like Monad), you can write class Foo[F[_]: Monad]. When you need to "partially apply" a type constructor with multiple parameters, like MonadError, the situation is slightly different.

    If you're using kind-projector, you can write the following:

    class DbSystemEnvironment[F[_]: MonadError[*[_], Throwable]]
    

    This is non-standard syntax, though, and it isn't currently included in Dotty's partial -Ykind-projector compatibility support. I'd recommend just desugaring the implicit parameter list:

    class DbSystemEnvironment[F[_]](implicit F: MonadError[F, Throwable]])
    

    This does exactly what you want, doesn't require an extra compiler plugin, and is much more future-proof.