2014-11-05 60 views
-2

在斯卡拉,它说的对象是单身。所以我想知道什么是对象的创建时间。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 
So when is the Singleton object created??

+1

Scala不是Java。构造函数没有使用类或对象的名称作为方法名称来定义。 – rightfold 2014-11-05 10:18:05

+0

你是对的,我刚刚改变,并验证它是在第一次通话期间创建的。 – cheneychen 2014-11-05 10:28:55

回答

0

Thank you rightføld, make some change and verified object just behaved as singleton, and created when first called

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() 
    } 
} 

output is:

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

It is much easier to try it in 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 
2

A scala object表现得像lazy val;它会在第一次被引用时被实例化。