我怎么知道,需要哪个隐式?

问题描述 投票:0回答:1

我有工作代码:

final case class Services[F[_]](c: Client[F], fooUrl: String)
                               (implicit cf: ConcurrentEffect[F]) {

  private val dsl = Http4sDsl[F]

  import dsl._

  def routes: HttpRoutes[F] = HttpRoutes.of[F] {
    case GET -> Root / "call" =>
      c.get(fooUrl) { res =>
        Applicative[F].pure {
          Response[F]().withEntity {
            res
              .body
              .through(text.utf8Decode)
              .map(msg => "Forwarded through Boo" |+| msg)
          }
        }
      }
  }

当我删除隐式导入implicit cf: ConcurrentEffect[F]时,编译器会抱怨:

[error] /home/developer/scala/boo-service/src/main/scala/com/sweetsoft/Services.scala:29:20: could not find implicit value for parameter instance: cats.Applicative[F]
[error]         Applicative[F].pure {
[error]                    ^
[error] /home/developer/scala/boo-service/src/main/scala/com/sweetsoft/Services.scala:26:48: could not find implicit value for evidence parameter of type cats.Defer[F]
[error]   def routes: HttpRoutes[F] = HttpRoutes.of[F] {
[error]                                                ^
[error] two errors found

我怎么知道,类型类implicit cf: ConcurrentEffect[F]丢失了?

scala scala-cats http4s
1个回答
0
投票

我认为,如果您查看cats-effect库的源代码,您会得到答案:

让我们转到ConcurrentEffect定义:

trait ConcurrentEffect[F[_]] extends Concurrent[F] with Effect[F] {...

嗯,现在让我们看看并发:

trait Concurrent[F[_]] extends Async[F] {...

异步:

trait Async[F[_]] extends Sync[F] with LiftIO[F] {...

下一个:

trait Sync[F[_]] extends Bracket[F, Throwable] with Defer[F] {

现在我们可以得出结论,ConcurrentEffect扩展了Defer

与您自己Applicative的相同尝试;)

为了快速处理此类错误-我认为您必须了解扩展层次结构-这样您才能快速确定所需的类型类

© www.soinside.com 2019 - 2024. All rights reserved.