Alexey Romanov
Alexey Romanov

Reputation: 170745

When are singleton objects constructed?

In

object O {
  // construction code and member initialization
}

construct, when is this code going to be run?

Upvotes: 2

Views: 315

Answers (2)

psp
psp

Reputation: 12158

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

Upvotes: 4

Michel Krämer
Michel Krämer

Reputation: 14647

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.

Upvotes: 12

Related Questions