0

Scala 2.13.10. Consider the following code:

object Hello extends App {
  def foo(implicit i: Int) = println(i)
  foo
  implicit val i: Int = 42
  foo
}

It compiles with the warning

 Reference to uninitialized value i
[warn]   foo

and prints

0
42

The expected behavior is that it compiles with an error of implicit not found.

Why does it behave the way it is?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Some Name
  • 8,555
  • 5
  • 27
  • 77
  • 5
    Because this is how classes/objects (and their fields) are initialized in JVM https://stackoverflow.com/questions/23093470/ Your "expected behavior" corresponds to a method body https://scastie.scala-lang.org/DmytroMitin/N43QMAPiRcyfcVpq5tHlrA/3 `val`-fields in an object can easily lead to NPE and similar exceptions https://scastie.scala-lang.org/DmytroMitin/N43QMAPiRcyfcVpq5tHlrA/8 It's safer to make them `lazy val` https://scastie.scala-lang.org/DmytroMitin/N43QMAPiRcyfcVpq5tHlrA/10 https://scastie.scala-lang.org/DmytroMitin/N43QMAPiRcyfcVpq5tHlrA/1 – Dmytro Mitin Dec 29 '22 at 15:51

0 Answers0