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

How do I know, which implicit that is needs?

我有一个工作代码:

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

我怎么知道缺少 class implicit cf: ConcurrentEffect[F] 类型?

我认为如果您查看 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 自己做 ;)

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