简体   繁体   中英

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

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM