Is this a bug? missing warning: Reference to uninitialized value one

382 views
Skip to first unread message

Bjorn Regnell

unread,
Mar 27, 2016, 4:05:38 PM3/27/16
to scala-user
Should/could the compiler give me a warning also for the nowarning object below?

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_45).
Type in expressions for evaluation. Or try :help.

scala> object nowarning {val many = Array.fill(10)(one); val one = 1}
defined object nowarning

scala> object warning {val a = one; val one = 1}
<console>:11: warning: Reference to uninitialized value one
       object warning {val a = one; val one = 1}
                               ^
defined object warning

scala>

Naftoli Gugenheim

unread,
Mar 27, 2016, 7:25:57 PM3/27/16
to Bjorn Regnell, scala-user

fill takes a call by name parameter, like Future, so it would be safe if it didn't call it until later (or never). The compiler doesn't know when it will be called.


--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

som-snytt

unread,
Mar 28, 2016, 12:53:01 AM3/28/16
to scala-user

I would say should and could.

The problem seems to be that by the time the check is performed (constructors phase), the RHS of the val only sees an anonymous function and not the reference to one.

Björn Regnell

unread,
Mar 28, 2016, 7:21:37 AM3/28/16
to scala-user

Well, it doesn't do what I meant. And I expect my future Scala students to make this mistake and getting rather confused... So I'd sure would like to get help from the compiler here, so that the mistake in the "nowarning"-object can be fixed by the human e.g. by turning "many" into a lazy val or change the order of declarations.

 

scala> object nowarning {val many = Array.fill(10)(one); val one = 1}

defined object nowarning

 

scala> nowarning.many

res0: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

 

Another similar mistake is indeed caught by the compiler, when it is even refusing to compile:

 

scala> {val many = Array.fill(10)(one); val one = 1}

<console>:12: error: forward reference extends over definition of value many

       {val many = Array.fill(10)(one); val one = 1}

                                  ^

The difference in behavior between members and local variables is easy to miss...

 

http://stackoverflow.com/questions/7762838/forward-references-why-does-this-code-compile

Naftoli Gugenheim

unread,
Mar 28, 2016, 3:51:45 PM3/28/16
to Björn Regnell, scala-user

Unfortunately the difference between locals and members is necessary, since initialization order of locals is much more deterministic.

Reply all
Reply to author
Forward
0 new messages