Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mark existing variable as candiate for implicit method

Tags:

scala

implicit

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.

like image 481
Raphael Roth Avatar asked Nov 18 '16 13:11

Raphael Roth


People also ask

What is implicit variable in Scala?

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 implicit request?

With implicit request It allows to get an instance of Messages automatically (the compiler will implicitly call request2Messages(yourRequest) when needed but you need to have an implicit request (or request header) in scope.

Which variable is an implicit parameter in Javascript?

Implicit Parameter - this The this parameter refers to the object that invoked the function. This is why this parameter is also known as function context. function myFunc() { 'use strict' return this; } myFunc();


1 Answers

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.

like image 61
Tyler Avatar answered Sep 28 '22 15:09

Tyler