Reputation: 194
As example I have this class
import java.sql.Timestamp
class Service(name: String, stime: Timestamp,
etime:Timestamp)
how to make it accept the following in implicit way, let us called stringToTimestampConverter
val s = new AService("service1", "2015-2-15 07:15:43", "2015-2-15 10:15:43")
Time have been passed as a string.
How to implement such a converter?
Upvotes: 0
Views: 66
Reputation: 5556
you have two ways, the first is having in scope a String => Timestamp implicit conversion
// Just have this in scope before you instantiate the object
implicit def toTimestamp(s: String): Timestamp = Timestamp.valueOf(s) // convert to timestamp
the other one is adding another constructor to the class:
class Service(name: String, stime: Timestamp, etime:Timestamp) {
def this(name: String, stime: String, etime: String) = {
this(name, Service.toTimestamp(stime), Service.toTimestamp(etime))
}
}
object Service {
def toTimestamp(s: String): Timestamp = Timestamp.valueOf(s) // convert to timestamp
}
Upvotes: 1