When are singleton objects built?

AT

object O {
  // construction code and member initialization
}

      

when will this code run?

+2


a source to share


2 answers


The code will be called when O

opened for 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 give



Before O
Hello From O
After O

      

It is not easy enough to define O

. Also the call won't work Class.forName("O")

as the name of the compiled object O$

, so call Class.forName("O$")

.

+12


a source


In the interest of building self-confidence:



scala> object O { println("hi") }
defined module O

scala> O
hi
res0: O.type = O$@51d92803

scala> O
res1: O.type = O$@51d92803

      

+4


a source







All Articles