2016-02-29 61 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 
}