Reputation: 85
I want to save the time when I instantiate my object.
With the following code, time changes each time I want to know the 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)
Both given dates are NOT equal ... any idea why!?
Thank you in advance!
UPDATE:
First, thank you for your responses!
I want to choose the Trait solution but this does not work anymore, if I want to use a separated method to retrieve the object ...
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)
But I can NOT touch "MyClass".
Any idea how to solve this?
Upvotes: 1
Views: 71
Reputation: 10020
I think you probably want to use a trait, which will simplify your code:
trait CreateTime {
val createTime: Long = System.currentTimeMillis()
}
You can attach it to your class either by extending it in the class definition:
class MyClass() extends CreateTime
Or when you create your object:
val obj = new MyClass with CreateTime
Also, pay attention to your variable names. What you called creationDate
really is not a date... it's a time (or a timestamp). It's important to be clear with your variable names.
Upvotes: 2
Reputation: 206796
One way to do this differently is by using a trait as a mixin:
trait CreationDate {
val creationDate: Long = System.currentTimeMillis()
}
val obj = new MyClass with CreationDate
println(obj.creationDate)
Thread.sleep(1000)
println(obj.creationDate)
Upvotes: 3
Reputation: 1617
obj
is an implicit conversion wrapper, so you are getting a new instance each time you use it.
if you add a println you will see what is happening
class DatedClass(myClass: MyClass) {
println("new instance")
val creationDate: Long = System.currentTimeMillis()
}
Upvotes: 1
Reputation: 1317
Your compiler will replace your calls to creationDate
with the implicit conversion. To call the method, the compiler will create a new wrapper object for each call to creationDate
. What the compiler does has the same effect as doing the following:
val obj = new MyClass
println(new DatedClass(obj).creationDate)
Thread.sleep(1000)
println(new DatedClass(obj).creationDate)
Since the constructor is called twice, the creation dates are different.
Upvotes: 2