繁体   English   中英

Scala:找不到 ContextShift[cats.effect.IO] 的隐式值

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

我刚开始使用 Scala 并想建立到我的数据库的连接。

(我的知识源于https://www.scala-exercises.org/上的 scala/doobie 教程)

现在这里是代码:

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

当我尝试构建我的代码时,我收到以下错误消息:

错误:(25, 53) 找不到 ContextShift[cats.effect.IO] 的隐式值:

  • 从你的效果库中导入 ContextShift[cats.effect.IO]

  • 如果使用 IO,请使用cats.effect.IOApp 或使用cats.effect.IO.contextShift xa <- HikariTransactor.newHikariTransactor[IO](

现在我有两个问题:

  1. 究竟是什么问题?
  2. 我如何解决它?

编译器在隐式作用域中找不到ContextShift[IO]实例的问题,这是某些方法所必需的(不确定究竟是哪个)。 您需要在隐式范围内声明自己的范围,例如

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

或作为错误提示消息, cats.effect.IOApp已将ContextShift[IO]声明为protected implicit def - 请参阅https://github.com/typelevel/cats-effect/blob/master/core/shared/src/main/scala/ cat/effect/IOApp.scala#L83可以在这段代码所在的地方使用和传递引用。 但要小心,因为它使用 Scala 默认的全局执行上下文。

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM