Defining a variable in scala with two implicits
Asked Answered
K

2

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 !

Kassey answered 28/7, 2016 at 11:9 Comment(0)
K
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.

Kingdom answered 28/7, 2016 at 11:48 Comment(0)
H
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.

Heti answered 28/7, 2016 at 11:58 Comment(2)
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 ambiguityFugger
You are right. I copied the wrong piece of code from IDE. I will update the answer. EDIT: Updated.Heti
K
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.

Kingdom answered 28/7, 2016 at 11:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.