Search code examples
scalascala-catscats-effect

Scala: Cannot find an implicit value for ContextShift[cats.effect.IO]


I just started with scala and want to build a connection to my DB.

(My knowledge stems from the scala/doobie Tutorial's on https://www.scala-exercises.org/)

Now here is the Code:

import doobie._
import doobie.implicits._
import cats.effect._
import cats.implicits._
import doobie.hikari._

...
val transactor: Resource[IO, HikariTransactor[IO]] =
    for {
      ce <- ExecutionContexts.fixedThreadPool[IO](32)         // our connect EC
      be <- Blocker[IO]                                       // our blocking EC
      xa <- HikariTransactor.newHikariTransactor[IO](
        "org.h2.Driver",                                      // driver classname
        "jdbc:mysql://localhost:3306/libraries",              // connect URL
        "root",                                               // username
        "",                                                   // password
        ce,                                                   // await connection here
        be                                                    // execute JDBC operations here
      )
    } yield xa

When I try to Build my Code i get the following error message:

Error:(25, 53) Cannot find an implicit value for ContextShift[cats.effect.IO]:

  • import ContextShift[cats.effect.IO] from your effects library

  • if using IO, use cats.effect.IOApp or build one with cats.effect.IO.contextShift xa <- HikariTransactor.newHikariTransactor[IO](

Now I've got two questions:

  1. What exactly is the problem?
  2. How do I fix it?

Solution

  • The problem that compiler cant find ContextShift[IO] instance in implicit scope, which is required for some of methods (not sure which exactly). You need to declare your own in implicit scope, like

    val dbExecutionContext = ExecutionContext.global // replace with your DB specific EC.
    implicit val contextShift: ContextShift[IO] = IO.contextShift(dbExecutionContext)
    

    or as error suggested message cats.effect.IOApp has declared ContextShift[IO] as protected implicit def - see https://github.com/typelevel/cats-effect/blob/master/core/shared/src/main/scala/cats/effect/IOApp.scala#L83 which you can use and pass reference in the place where this code is located. But be careful, because it uses Scala default global execution context.

    Hope this helps!