thesamet
thesamet

Reputation: 6582

Marking an argument implicit inside a method

I have a method that calls a few other methods that make use of an implicit of type Foo. I'd like to make f implicit inside Foo. This is how I do it:

def myMethod(a: Int, f: Foo) = {
  implicit val implicitF = f;
  somethingThatNeedsFoo(a) 
}

I don't want to mark f implicit in the signature of myMethod since Foos are not implicit in the context that myMethod is being used. My question: is there a more idiomatic (or concise) way to achieve this effect than using a temporary variable?

Upvotes: 7

Views: 728

Answers (2)

Debilski
Debilski

Reputation: 67888

I’ve never seen this being actually used but you can avoid binding the variable to a name. Using, of course, the underscore:

implicit val _ = f

I’d advise against this usage, though.

Upvotes: 6

Jed Wesley-Smith
Jed Wesley-Smith

Reputation: 4706

You can pass implicit parameters explicitly, so even though there's no Foo in the implicit scope of the caller, the caller can just pass it explicitly.

As commented, you can use this same trick to pass the Foo to somethingThatNeedsFoo:

 def myMethod(a: Int, f: Foo) =
   somethingThatNeedsFoo(a)(f) 

Upvotes: 4

Related Questions