包对象何时初始化? [英] When are package objects initialized?
本文介绍了包对象何时初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我定义了包对象
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?
换句话说,什么决定了more.time
的值?
程序首次启动时是否进行评估?还是第一次访问它?还是第一次访问more
?
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?
推荐答案
很容易检查:
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)
}
给予:
1339394348495
1339394349496
第二次是大约1000毫秒之后,所以这是第一次访问包对象,就像处理其他任何对象一样.
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.
这篇关于包对象何时初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文