首页 > 解决方案 > 我怎么知道,需要哪个隐含的?

问题描述

我有一个工作代码:

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)
          }
        }
      }
  }

当我删除隐式 importimplicit 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]缺少类型类?

标签: scalascala-catshttp4s

解决方案


我认为如果您查看猫效应库的来源,您可以获得答案:

让我们看看 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自己做;)

要快速处理此类错误-我认为您必须了解扩展层次结构-以便您可以快速找出所需的类型类


推荐阅读