2014-11-05 3 views
-2

В Scala, указанный объект является одноэлементным. Поэтому мне интересно, какое время создания объекта.Время создания объекта 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 
So when is the Singleton object created??

+1

Scala не является Java. Конструкторы не определяются с использованием имени класса или объекта в качестве имени метода. – rightfold

+0

Вы правы, я просто изменился и подтвердил, что он создан, когда во время первого звонка. – cheneychen

ответ

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; он будет создан при первом упоминании.

Смежные вопросы