在Scala中,隐式使用参数,但不要隐式传递它

时间:2014-05-26 19:17:05

标签: scala

假设我想显式地将ExecutionContext作为参数传递给方法,但希望在该方法的主体中隐式使用该上下文。我可以使用以下简单的代码片段实现此目的:

  def run(foo: Unit => Unit,
          ex1: ScheduledExecutorService) {
    import scala.concurrent.duration._
    implicit val ex2 = ex1
    scheduleAtFixedRate(foo, 1.seconds, 3.seconds) // pass ex2 implicitly, not explicitly
  }

有没有办法在不将ex1重新分配给ex2的情况下执行此操作,但仍需要明确地传递参数?

2 个答案:

答案 0 :(得分:2)

没有。如果要求显式传递参数,则在函数体内隐式使用它的唯一方法是将其重新分配给隐式变量。然而,为什么你会想要这样做无视我的推理。

答案 1 :(得分:0)

隐式参数的解析是基于类型的。我能想到的唯一方法(特别是因为你想从调用者那里接收参数)是让run隐式接受执行者服务,如:

  def run(foo: Unit => Unit)(implicit ex1: ScheduledExecutorService) {
    // no need for the below; ex1 already used for implicit resolution
    // implicit val ex2 = ex1
  }

当然,这意味着run方法的调用者必须定义用于执行者服务的隐式值,或者明确地传递它,如下所示:

run(someFoo)(someScheduledExecutorService)