Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a variable in scala with two implicits

I came across an interesting post on twitter by scalaLang. Where this code compiles and works

class A(implicit implicit val b: Int) 

val objA = new A()(42)

Can someone please explain me how is it working? I read the documentation of implicits but didn't found a case like this. Please explain me what's happening here.

Any help is appreciated !

like image 866
Shivansh Avatar asked Jul 28 '16 11:07

Shivansh


People also ask

How do I use Implicits in Scala?

Scala provides an implicit keyword that can be used in two ways: method or variable definitions, and method parameter lists. If this keyword is used on method or variable definitions, it tells the compiler that those methods or variable definitions can be used during implicit resolution.

What is Implicits 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.

Where does Scala look for Implicits?

When an implicit value is required, the Scala compiler would first look into the current scope to find the required implicit value that can act as a function for the type conversion required. The current scope used as implicit scope include: Local scope.

What is implicit in spark?

implicits object gives implicit conversions for converting Scala objects (incl. RDDs) into a Dataset , DataFrame , Columns or supporting such conversions (through Encoders).


2 Answers

After some digging I confirm what @Alexey Romanov said. Consider following example:

case class A(implicit implicit val a: Int)

def foo(x: Int)(implicit y: Int): Int = x * y

We could use it like this:

implicit val m: Int = 2
val myA = A()

And the following application:

val myAA = A()(2)
val n = myAA.a 
foo(3)

Now, foo(3) obviously yields 6 since it takes n implicitly. If we change the class to

case class A(implicit val a: Int)

it does not change the behavior of foo. Therefore, we arrive to the same conclusion that @Alexey - first implicit indicates that the constructor parameter can be passed implicitly; whereas the second one defines implicit value - even though in this case, they do the same thing.

like image 172
sebszyller Avatar answered Sep 28 '22 18:09

sebszyller


You can have implicit before the last parameter list of a class or a method, and also before any member of a class or a trait. This simply combines both, which is probably legal just because forbidding it would make the language specification and the parser slightly more complex for no real benefit. I don't think there is any reason to ever use this or any difference from writing implicit once.

like image 23
Alexey Romanov Avatar answered Sep 28 '22 16:09

Alexey Romanov