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 !
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.
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.
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.
implicits object gives implicit conversions for converting Scala objects (incl. RDDs) into a Dataset , DataFrame , Columns or supporting such conversions (through Encoders).
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.
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.
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