When are package objects initialized?

If I define a package object

package com.something.else

package object more {
    val time = System.currentTimeMillis
    // ... other stuff ...
}

which is then imported somewhere into the source code.

import com.something.else.more

When is this object (and its members) initialized / built?

In other words, what determines the meaning more.time?
Is it evaluated when the program begins? Or at first access? Or at first access more?

+5
source share
1 answer

Easy to check:

package something

package object more {
  val time = System.currentTimeMillis
}

// in separate file:
package something.more

object Test extends App {
  val now = System.currentTimeMillis

  Thread.sleep(1000)

  println(now)
  println(time)
}

gives:

1339394348495
1339394349496

The second time is ~ 1000 ms later, so the first time you access the package object, like any other object.

+7
source

All Articles