scala对象的创建时间

时间:2014-11-05 10:10:55

标签: scala object singleton

在Scala中,它说的对象是单身。所以我想知道对象的创建时间是什么。

我创建了两个scala文件,如下所示:

object Singleton {
def Singleton() = {
    val time = System.currentTimeMillis()
    println("creation time: " + time)
}
def getTime() = {
    val time = System.currentTimeMillis()
    println("current time: " + time)
}
}

object Test {
def main(args: Array[String]) = {
    Singleton.getTime()
    Thread sleep 10000
    Singleton.getTime()
}
}

输出是:

current time: 1415180237062
current time: 1415180247299
那么什么时候创建Singleton对象?

3 个答案:

答案 0 :(得分:4)

在Scala REPL中尝试它会容易得多:

scala> object Singleton {
     |   println("creation time: " + System.nanoTime())
     |   def getTime = println("current time:  " + System.nanoTime())
     | }
defined module Singleton

scala> def test = {
     |   println("before call:   " + System.nanoTime())
     |   Singleton.getTime
     |   Singleton.getTime
     | }
test: Unit

scala> test
before call:   1194990019328128
creation time: 1194990019677693
current time:  1194990019889606
current time:  1194990020062275

答案 1 :(得分:3)

scala object的行为类似于lazy val;它将在第一次被引用时被实例化。

答案 2 :(得分:0)

谢谢rightføld,进行一些更改并验证对象只是表现为单身,并在第一次调用时创建

object Singleton {
  def getTime() = {
    val time = System.currentTimeMillis()
    println("current time: " + time)
  }
  private def init() {
    val time = System.currentTimeMillis()
    println("creation time: " + time)
  }
  init()
}

object Test {
  def main(args: Array[String]) = {
    val time = System.currentTimeMillis()
    println("before call: " + time)
    Singleton.getTime()
    Thread sleep 10000
    Singleton.getTime()
  }
}

输出是:

before call: 1415183199534
creation time: 1415183199732
current time: 1415183199732
current time: 1415183209735