Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marking an argument implicit inside a method

Tags:

scala

implicit

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?

like image 786
thesamet Avatar asked Aug 23 '12 03:08

thesamet


People also ask

What is implicit parameter?

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.

How many implicit parameters can an instance method have?

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.

What is an implicit view?

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.

How do you use implicit in Scala?

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.


2 Answers

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.

like image 71
Debilski Avatar answered Oct 04 '22 06:10

Debilski


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) 
like image 37
Jed Wesley-Smith Avatar answered Oct 04 '22 06:10

Jed Wesley-Smith