简体   繁体   中英

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?

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.

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM