Forward References - why does this code compile?

后端 未结 2 1791
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 05:34

Consider this snippet:

 object A {
     val b = c
     val c = \"foo\"
 }
 println( A.b )   // prints \"null\"

As part of a larger program,

2条回答
  •  旧时难觅i
    2020-11-30 06:28

    It is because of outdated version of Scala.

    With Scala 2.11.5 it compiled with warning or doesn't compiled at all:

    C:\Users\Andriy\Projects\com\github\plokhotnyuk>scala
    Welcome to Scala version 2.11.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_31).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> { object A { val b = c; val c = "foo" }; println(A.b) }
    :9: warning: Reference to uninitialized value c
                  { object A { val b = c; val c = "foo" }; println(A.b) }
                                       ^
    null
    
    scala> { val b = c; val c = "foo"; println(A.b) }
    :9: error: forward reference extends over definition of value b
                  { val b = c; val c = "foo"; println(A.b) }
                            ^
    

提交回复
热议问题