這是你有什麼:
scala> object Foo {
| ???
| val x = 100
| }
defined object Foo
scala> object Bar {
| import Foo._
| def speak = "bar!"
| }
defined object Bar
scala> Bar.speak
res0: String = bar!
scala> Bar.speak
res1: String = bar!
import Foo._
意味着美孚的編譯目的來解析名稱的成員將在範圍內都有效。 這並不意味着Foo
必須在這一點上初始化 - 斯卡拉在這裏懶惰。 現在用這個例子對比:
scala> object Foo {
| ???
| val x = 100
| }
defined object Foo
scala> object Bar {
| val blowUp = Foo.x
| def speak = "bar!"
| }
defined object Bar
scala> Bar.speak
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
... 37 elided
它迫使Foo
因爲其在自己的初始化而這又是 調用speak
觸發使用Foo.x
得到初始化。簡化示例:
scala> object Foo {
| ???
| val x = 100
| }
defined object Foo
還沒爆炸呢。 Foo
未初始化。
scala> Foo.x
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
... 35 elided
現在我們強制Foo
得到初始化。
總之這裏有兩個重要的事情:1)在參考/呼叫延遲初始化和2)進口不會導致初始化。
導入從來沒有影響。 –