When are package objects initialized?

package, scala

Solution

It's 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 it's when the package object is first accessed, as it would be with any other object.

Problem

If I define a package object ``` package com.something.else package object more { val time = System.currentTimeMillis // ... other stuff ... } ``` which is then imported somewhere in the source code. ``` import com.something.else.more ``` When is this object (and its members) initialized/constructed? In other words, what determines the value of `more.time`? Is it evaluated when the program first starts? Or the first time it is accessed? Or the first time `more` is accessed?

Original source