Could not find implicit value for parameter F: cats.Applicative[F] with Sync and Temporal

375 Views Asked by At

Basically, I just want to add a sleep somewhere, but I don't understand how to provide the implicit Applicative needed.

I'm using cats effect 3.5. It's totally new to me. I have been using ZIO for 2 years, but I'm lost about how to jungle with the generic wrappers in cats effect.

Let's consider a basic code of a heath-check route, for example:

class Routes[F[_]: Sync] extends Http4sDslExt[F, Nothing] {
  import Routes._

  val routes: HttpRoutes[F] = HttpRoutes.of {
    case (HEAD | GET) -> Root / PathPrefix => Response[F]().withStatus(Ok).pure[F]
  }

}

I naively tried to add Temporal and do a sleep like this:

class Routes[F[_]: Sync: Temporal] extends Http4sDslExt[F, Nothing] {
  import Routes._

  val routes: HttpRoutes[F] = HttpRoutes.of {
    case (HEAD | GET) -> Root / PathPrefix =>
      for {
        resp <- Response[F]().withStatus(Ok).pure[F] // No implicits found for parameter F: Applicative[F]
        _ <- Temporal[F].sleep(5.seconds)
      } yield resp
  } // No implicits found for parameter Monad $F$0F: Monad[F_]

Should I define and provide an Applicative that implements both Sync and Temporal? How can I do that?

2

There are 2 best solutions below

0
Terry BRUNIER On

I solved this issue by using only Temporal:

class Routes[F[_]: Temporal]

It makes sense that a synchronous effect is not expected to wait, but I would be happy to have more advanced explanations.

0
Daenyth On

This happens because both Sync and Temporal extend Applicative (indirectly). So when the compiler tries to find Applicative[F], it has two unrelated instances in scope - Sync[F] and Temporal[F]. It doesn't have any way to decide between them, so it fails to find the implicit.

In this case the code doesn't need Sync at all, so you can remove it:

class Routes[F[_]: Temporal]

If the code did need to use both constraints, then it could use Async[F] instead, which extends both Sync and Temporal, providing both capabilities

class Routes[F[_]: Async]