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?
Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.
An implicit parameter list (implicit $p_1$,$\ldots$,$p_n$) of a method marks the parameters $p_1 , \ldots , p_n$ as implicit. A method or constructor can have only one implicit parameter list, and it must be the last parameter list given.
Thoughts and feelings are “implicit” if we are unaware of them or mistaken about their nature. We have a bias when, rather than being neutral, we have a preference for (or aversion to) a person or group of people.
Parameter lists starting with the keyword using (or implicit in Scala 2) mark contextual parameters. Unless the call site explicitly provides arguments for those parameters, Scala will look for implicitly available given (or implicit in Scala 2) values of the correct type.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With