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

Scala: Pass function A as a parameter through function B which B declare an implicit parameter for function A

假设我有 2 个方法,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)

但是 B(A) 行 "Cannot find any HTTP Request here"

有一个错误

我只想将函数 A 作为参数传递给方法 B,而不是在我调用方法 B 时传递。

我试过像这样显式声明 t,它有效

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

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

但我真的很想让它隐含

有办法吗??

你试过这个吗?当你调用 A 时,你的隐式需要在范围内,所以我认为这会起作用:

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

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

要在呼叫站点获得 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中失去了隐含性。为避免这种情况,您需要 implicit function types,当前 Scala 不支持。