Scala:通过函数B将函数A作为参数传递,B为函数A声明一个隐式参数

时间:2017-07-18 07:29:35

标签: scala implicit

假设我有两个方法,A,B和4个类,C,D,E,T。

def A(c: C)(implicit t: Request[T]): D { ... }

def B(fn: C => D): E {
  implicit val t // I have to declare implicit val for A here
  fn(c)
  ...
}

然后我想用A作为参数调用方法B

B(A)

但是有一个错误"在这里找不到任何HTTP请求"在B行(A)

我只想传递函数A,就像要在方法B中执行的参数一样,而不是在我调用方法B时。

我尝试明确表示这样,它可以正常工作

def A(c: C, t: Request[T]): D { ... }

def B(fn: C => D): E {
  fn(c, t)
  ...
}

但我真的想隐瞒

有办法吗?

2 个答案:

答案 0 :(得分:1)

要在呼叫站点获取B(A),例如

def B(fn: C => Request[T] => D): E = {
  val t = ... // no point making it implicit unless you use it elsewhere
  fn(c)(t)
  ...
}

应该有效(我现在无法检查,但如果没有,请尝试B(A _))。

但你仍然在B内失去隐含性。为避免这种情况,您需要enter image description here,这是当前Scala不支持的。

答案 1 :(得分:0)

你试过这个吗?当你调用A时,你隐含的需要在范围内,所以我认为这将有效:

def A(c: C)(implicit t: Request[T]): D { ... }

def B(fn: C => D)(implicit t: Request[T]): E {
  fn(c)
  ...
}