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

Suppose I have 2 methods, A, B, and 4 classes, 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)
  ...
}

Then I want to call method B with A as a parameter

B(A)

But there is an error "Cannot find any HTTP Request here" at line B(A)

I just want to pass function A like a parameter to be executed in method B, not when I Call method B.

I tried declaring t explicitly like this, it works

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

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

But I really want to make it implicit

Is there a way to do this??

Upvotes: 0

Views: 72

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

To get B(A) at call site, something like

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

should work (I can't check at the moment, but if it doesn't, try B(A _) as well).

But you still lose implicitness inside B. To avoid this, you would need implicit function types, which current Scala doesn't support.

Upvotes: 1

sheunis
sheunis

Reputation: 1544

Have you tried this? Your implicit needs to be in scope when you call A, so I think this will work:

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

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

Upvotes: 0

Related Questions