6

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 !

Shivansh
  • 3,454
  • 23
  • 46

2 Answers2

3

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.

sebszyller
  • 853
  • 4
  • 10
  • Correct me if I'm wrong but `foo` takes `m` implicitly, it's hidden by a fact that `n ==m`. `n` isn't declared as implicit so it can't be used that way, moreover if one would declare two values of the same type implicit in the same scope, compiler would raise an error because of ambiguity – Tomasz Błachut Jul 28 '16 at 12:16
  • You are right. I copied the wrong piece of code from IDE. I will update the answer. EDIT: Updated. – sebszyller Jul 28 '16 at 12:22
2

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487