tags:

views:

146

answers:

2

In

object O {
  // construction code and member initialization
}

construct, when is this code going to be run?

+8  A: 

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.

Michel Krämer
Regarding `Class.forName("O")`, that only won't work because the class name for `object O` is actually `"O$"`. If you call `java.lang.Class.forName("O$")`, it will indeed execute the initialisation block.
Kristian Domagala
Thanks, I fixed that.
Michel Krämer
Very good. That's what I hoped for.
Alexey Romanov
I see now that my answer is totally redundant. Conclusion: I am a better answer writer than answer reader.
extempore
+3  A: 

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
extempore