In
object O {
// construction code and member initialization
}
construct, when is this code going to be run?
In
object O {
// construction code and member initialization
}
construct, when is this code going to be run?
The code will be called when O
is accessed the first time (some method or some property). For example the following program
object O {
println("Hello from O")
def doSome() {}
}
object App extends Application {
println("Before O")
O.doSome()
println("After O")
}
will yield
Before O
Hello From O
After O
It's not enough to simply define O
. Also it won't work to to call Class.forName("O")
since the compiled object's name is O$
, so calling Class.forName("O$")
will do.
In the interests of building self-reliance:
scala> object O { println("hi") }
defined module O
scala> O
hi
res0: O.type = O$@51d92803
scala> O
res1: O.type = O$@51d92803