在Scala中创建多态构造函数的正确方法是什么?一方面,我可以使用伴侣对象:
class UserRecord (override val userID: String,
override val rep: Int) extends Record
object UserRecord extends Record {
def apply(line: String) = {
val elem = XML.loadString(line)
val userID = elem \ "@Id" text
val rep = (elem \ "@Reputation" text).toInt
val out = new UserRecord(userID, rep)
out
}
}
但是这会丢失一些封装,并且对没有new
的对象的调用掩盖了正在创建非单例对象的事实。另一方面,我可以使用一系列备用构造函数,这有点笨重:
class UserRecord (override val userID: String,
override val rep: Int) extends Record {
def this(t: Tuple2[String, Int]) = this(t._1, t._2)
def this(line: String) = this({
val elem = XML.loadString(line)
val userID = elem \ "@Id" text
val rep = (elem \ "@Reputation" text).toInt
val out = (userID, rep)
out
})
}
我也在寻找避免使用.tupled
使用第一个替代构造函数的方法,但还没有真正破解那个问题。