3

I was trying to find any information (docs, specs, etc) on this but the topic seems to be pretty ungoogleable. I'm asking for any references on why the following works.

trait Foo[A]

package bar {
  trait Bar
  private[bar] object Bar {
    implicit val b: Foo[Bar] = null
  }
}

import bar._
def foo[A: Foo](a: A): Foo[A] = implicitly[Foo[A]]

foo(new Bar) // compiles

Somehow, the compiler was able to locate the implicit value of type Foo[Bar] in the package-private companion object Bar. Why?

To clarify my question. Everything changes is we change the companion object like shown below (implicit value is private but enclosing object is not). The code above won't compile with this Bar.

package bar {
  trait Bar
  object Bar {
    private implicit val b: Foo[Bar] = null
  }
}

Is there some docs/specs that explain why this happens?

Vladimir Kostyukov
  • 2,492
  • 3
  • 21
  • 30
  • 1
    possible duplicate of [Where does Scala look for implicits?](http://stackoverflow.com/questions/5598085/where-does-scala-look-for-implicits) –  Jun 16 '15 at 00:12
  • @I.K. Sorry, maybe I wasn't clear in my question. It's well known that scala compiler is looking for implicits in the companion object. It wasn't a surprise for me. What I asking is why it still works even if the companion object is private. Would be great if you could link answer in the linked question that explains it. – Vladimir Kostyukov Jun 16 '15 at 00:41
  • The fact that the companion object is qualified private has nothing to do with it. All that means is that the object is only accessible in the package `bar` in your example. –  Jun 16 '15 at 00:58
  • In edited post, the second implicit is private so it is not accessible outside the object, that's why it doesn't compile. In the first it is not private so it is accessible! –  Jun 16 '15 at 01:48
  • 2
    I'd never noticed this before. I guess it makes sense, but it does lead to some [kind of funny situations](https://gist.github.com/travisbrown/0b516c15dc2188e1b356). – Travis Brown Jun 16 '15 at 04:16

0 Answers0