簡體   English   中英

是否可以在Scala中實現類構造函數類型轉換器

[英]Is it possible to implement a class constructor type converter in Scala

例如我有這個課

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

時間已作為字符串傳遞。

如何實現這樣的轉換器?

您有兩種方法,第一種是在范圍內使用String => Timestamp隱式轉換

// 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM