例如我有这个课程
import java.sql.Timestamp
class Service(name: String, stime: Timestamp,
etime:Timestamp)
如何让它以隐式方式接受以下内容,让我们调用stringToTimestampConverter
val s = new AService("service1", "2015-2-15 07:15:43", "2015-2-15 10:15:43")
时间已经作为字符串传递。
如何实现这样的转换器?
答案 0 :(得分:1)
你有两种方式,第一种是在范围内有一个String =>时间戳隐式转换
// Just have this in scope before you instantiate the object
implicit def toTimestamp(s: String): Timestamp = Timestamp.valueOf(s) // convert to timestamp
另一个是在类中添加另一个构造函数:
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
}