Scala - 在覆盖的对象创建上节省创建时间

时间:2013-12-10 20:21:26

标签: scala implicit

我希望在实例化对象时节省时间。

使用以下代码,每次我想知道creationDate时,时间都会改变:

class MyClass()

class DatedClass(myClass: MyClass) {
  val creationDate: Long = System.currentTimeMillis()
}

implicit def CachedWrapperClassifier(myClass: MyClass) = {
  new DatedClass(myClass)
}

val obj = new MyClass
println(obj.creationDate)  
Thread.sleep(1000)
println(obj.creationDate)

两个给定日期都不相等......任何想法为什么!?

提前谢谢!

更新

首先,感谢您的回复!

我想选择Trait解决方案,但如果我想使用分离的方法来检索对象,这不再有用了......

trait CreationTime {
  val creationTime: Long = System.currentTimeMillis()
}

class MyClass()

def getMyClass: MyClass = {
  new MyClass with CreationTime
}

val obj = getMyClass
println(obj.creationTime) // creationTime is not accessible
Thread.sleep(1000)
println(obj.creationTime)

但我无法触及" MyClass"。

知道如何解决这个问题吗?

4 个答案:

答案 0 :(得分:3)

另一种方法是将特质用作混合物:

trait CreationDate {
  val creationDate: Long = System.currentTimeMillis()
}

val obj = new MyClass with CreationDate
println(obj.creationDate)  
Thread.sleep(1000)
println(obj.creationDate)

答案 1 :(得分:2)

您的编译器将使用隐式转换替换您对creationDate的调用。要调用该方法,编译器将为每次调用creationDate创建一个新的包装器对象。编译器的作用与执行以下操作具有相同的效果:

val obj = new MyClass
println(new DatedClass(obj).creationDate)  
Thread.sleep(1000)
println(new DatedClass(obj).creationDate)

由于构造函数被调用两次,因此创建日期不同。

答案 2 :(得分:2)

我想您可能想要使用特性,这将简化您的代码:

trait CreateTime {
    val createTime: Long = System.currentTimeMillis()
}

您可以通过在类定义中扩展它来将它附加到您的类:

class MyClass() extends CreateTime

或者在您创建对象时:

val obj = new MyClass with CreateTime

另外,请注意您的变量名称。你所谓的creationDate真的不是约会......它是时间(或时间戳)。用变量名清楚是很重要的。

答案 3 :(得分:1)

obj是一个隐式转换包装器,因此每次使用它时都会获得一个新实例。

如果添加println,您将看到正在发生的事情

class DatedClass(myClass: MyClass) {
  println("new instance")
  val creationDate: Long = System.currentTimeMillis()
}
相关问题