When are package objects initialized?

喜你入骨 提交于 2019-12-12 11:12:31

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10973692/when-are-package-objects-initialized

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!