2016-02-29 38 views
0

作为例子,我有这个类来实现类构造函数类型转换器是否有可能在斯卡拉

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") 

时间已经过去了。

如何实现这样的转换器?

回答

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 
}