Implicits are visible inside themselves?

Okay, this one is kind of weird. This example came up at work:

case class Foo()

implicit val foo: Foo = implicitly[Foo]

println(s"It is ${implicitly[Foo]}")

To my astonishment, this compiles, and prints “It is null”.

What’s going on here? This isn’t anything critical, mostly just trying to understand it, but it seems to imply that the presence of the implicit value is visible inside of its definition, which is surprising…

Before a val is initialized, it has a default value, which is null for an AnyRef:

**Welcome to Scala version 2.10.6 (OpenJDK 64-Bit Server VM, Java 1.8.0_201).
Type in expressions to have them evaluated.
Type :help for more information.

class Foo
defined class Foo
val foo: Foo = foo
:8: warning: value foo does nothing other than call itself recursively
val foo: Foo = foo
^
foo: Foo = null**

Unfortunately that is correct. A (pretty ugly) workaround is:

implicit val foo: Foo = {
  val foo = null
  implicitly[Foo]
}

By shadowing the name foo, the implicit foo is no longer accessible and therefore no longer eligible as an implicit Foo in that scope.

Fascinating – never occurred to me that that actually compiles. Is there a reasonable use case for this sort of recursive val, or is just a side-effect of recursive defs being sensible?

Thanks for the pointer!