Mark existing variable as candiate for implicit method
Asked Answered
Z

1

7

I try to write a method which should use a variable from the surrounding scope. The problem is that I cannot access the part of the code where the variable is defined. Something like this:

object Example extends App {

  val myvar = 1.0 // cannot change that code

  def myMethod()(implicit value:Double) = {
      print(value)
  }

  myMethod()
}

This fails because myMethod cannot find a suitable implicit for value.

is there a way to "mark" value as implicit after it has been defined, other than defining a new implicit variable pointing to value?

Background: We use Spark-Notebook where the SparkContext (named sc) is created automatically. As sc is a commonly known name for this variable in the community, we would prefer not to introduce another variable name.

Zlatoust answered 18/11, 2016 at 13:18 Comment(5)
what's wrong with implicit val myvarAgain = myvar?Molding
@EduardoParejaTobes I'd like not to introduce an additional variable...Zlatoust
myMethod()(myvar)Uncounted
What you want to do is to pass the spark context implicitly to a method? Why not explicitly?Selective
(Spark Notebook dev here) If you really realliy need the implicit, consider changing the source code and making a custom build: github.com/andypetrella/spark-notebook/blob/master/conf/scripts/…Selective
S
6

If you just don't want to have an instance of SparkContext that isn't labeled as sc you could assign it to an implicit-underscore variable like this:

implicit val _: SparkContext = sc

That would create an implicit variable of the correct type in scope for your function to use.


Alternatively you can always pass implicit variables explicitly, in your example above you could do

myMethod()(myvar)

and that is the solution that I would use.

Souter answered 18/11, 2016 at 14:33 Comment(2)
implicit val _ isn't an unnamed val. Its name is the underscore, and you can access it with back-ticks: println(`_`). (Does not work in the REPL)Villeneuve
Cool thanks, I didn't know you could access it like that! I will edit my answer.Souter

© 2022 - 2024 — McMap. All rights reserved.