[scala] Preventing access to an val field under initialization

View: New views
2 Messages — Rating Filter:   Alert me  

[scala] Preventing access to an val field under initialization

by _retronym :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I just hit a bug in scalac [1] which is caused by using the still null value of a field during the initialiazation of that field. Essentially, it is the same as the following:

~> cat test.scala
object A { val a: AnyRef = { println("a = " + a);  ""} }
A.a
~> scala test.scala
a = null

This can be the source of subtle bugs. My mental model is that using vals rather than vars avoids such problems. Would it be feasible to add a -X option to fail fast in this case? I guess this would involve some extra bookkeeping about which fields are currently being initialized, similar to the handling of lazy vals.

-jason

[1] https://lampsvn.epfl.ch/trac/scala/ticket/2493


Re: [scala] Preventing access to an val field under initialization

by Paul Phillips-3 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On Mon, Oct 19, 2009 at 11:02:05PM -0500, Jason Zaugg wrote:
> This can be the source of subtle bugs. My mental model is that using
> vals rather than vars avoids such problems. Would it be feasible to
> add a -X option to fail fast in this case?

As I mention in the ticket, this is exactly what -Xcheckinit does.

--
Paul Phillips      | On two occasions, I have been asked, 'Mr. Babbage, if you
Moral Alien        | put into the machine wrong figures, will the right answers
Empiricist         | come out?' I am not able to rightly apprehend the kind of
i'll ship a pulp   | confusion of ideas that could provoke such a question.