Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 282
Malabarba Avatar asked Jun 11 '12 01:06

Malabarba


1 Answers

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.

like image 199
Luigi Plinge Avatar answered Oct 23 '22 08:10

Luigi Plinge