10

Possible Duplicate:
Forward References - why does this code compile?
Scala and forward references

object Main extends App {
  val a = 4
  val b = a + c
  val c = 5
  println(b) // => 4
}

This will print 4 as c apparently is 0 when b is assigned. a and c are values, so they should not be 0 in one moment, and 5 in the next. In Scala, they should be immutable, right?

Shouldn't I at least get some sort of warning? Of course, in the example above, you have to be an idiot to miss that, but in more complicated cases, it can be hard to tell what order to put it.

I am of course aware that I can use lazy val b = ... but what if I think I've put it in the right order, when I really haven't. Isn't it dangerous as hell not getting any warning at all on this? This runs just fine!? How does this get passed both Scala IDE and the compiler? Is it on purpose? Or is it a bug that cannot be fixed? :/

:)

Community
  • 1
  • 1
kornfridge
  • 5,102
  • 6
  • 28
  • 40
  • 1
    These should answer the question: http://stackoverflow.com/questions/12184997/scala-and-forward-references and http://stackoverflow.com/questions/13504809/scala-strange-behavior-in-class-object-initialization/13504969#13504969 – jcern Jan 09 '13 at 14:18
  • 1
    @jcern : That thread explains why it *happens*, but not *why* it is allowed by *design*. Why is this dangerous behavior not being fixed / not on the SIPs? A link to comment/blog post from one of the Scala designers would be awesome here :) – kornfridge Jan 09 '13 at 15:09
  • 1
    @kornfridge see [this thread](http://scala-programming-language.1934581.n4.nabble.com/scala-Initialization-Order-td1999887.html). In short: nobody come up with an idea on such compilation scheme which will satisfactory solve this problem (from many points of view: speed, compability, etc). – om-nom-nom Jan 09 '13 at 19:55

0 Answers0