gpt4 book ai didi

Scala 隐式搜索

转载 作者:行者123 更新时间:2023-12-02 07:17:57 25 4
gpt4 key购买 nike

在带有猫的 Scala 中:

import scala.concurrent.{Future, ExecutionContext}
implicit def futureFunctor
(implicit ec: ExecutionContext): Functor[Future] = …

Whenever we summon a Functor for Future , either directly using Functor.apply or indirectly via the map extension method, the compiler will locate futureFunctor by implicit resolu on and recursively search for an ExecutionContext at the call site. This is what the expansion might look like:

// We write this:
Functor[Future]
// The compiler expands to this first:
Functor[Future](futureFunctor)
// And then to this:
Functor[Future](futureFunctor(executionContext))

好的,我试试看:

  import scala.concurrent.{Future, ExecutionContext}
implicit def futureFunctor
(implicit ec: ExecutionContext): Functor[Future] = new Functor[Future] {
override def map[A, B](fa: Future[A])(f: A => B): Future[B] =fa map f
}

Functor[Future].map(Future.successful(2))(_+1)

但是得到一个异常(exception):

Error:(29, 10) could not find implicit value for parameter instance: cats.Functor[scala.concurrent.Future]
Functor[Future].map(Future.successful(2))(_+1)

我通常会修复为:

import cats.instances.future._

但修复没有帮助。而且我不能导入它,因为在范围内隐式 futureFunctor 已经定义。

我错过了什么?

最佳答案

But get an exception:

这不是异常,这是编译错误。

当你写 implicit def futureFunctor(implicit ec: ExecutionContext) = ...这意味着应该有一个 ExecutionContext在适用范围。但是当你调用Functor[Future]时却没有在 Functor[Future].map(Future.successful(2))(_+1) .

尝试

import scala.concurrent.ExecutionContext.Implicits.global

implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))

或类似的东西。

顺便说一句,如果你import cats.instances.future._并定义您的本地 Functor[Future]看来猫的会用到。

关于Scala 隐式搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56144100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com