我正在寻找一种方法来为一个案例类使用两种不同的形式。我试图用额外的构造函数来做到这一点,但失败了。看代码片段:
case class LoginDetails(password: String, field3: Option[Int], field4: String)
case class User(username: String, loginDetails: LoginDetails) {
def this(username: String, password: String, field3: Option[Int], field4: String) = this(username, LoginDetails(password, field3, field4))
// some logic inside
}
val loginDetailsForm = Form(
mapping(
"password" -> text,
"field3" -> optional(number),
"field4" -> text
)(LoginDetails.apply)(LoginDetails.unapply))
val oldForm = Form(
mapping(
"username" -> email,
"password" -> text,
"field3" -> optional(number),
"field4" -> text
)(User.apply)(User.unapply))
val newForm = Form(
mapping(
"username" -> email,
"loginDetails" -> loginDetailsForm.mapping
)(User.apply)(User.unapply))
我想要做的是支持两个 API(新的和旧的),但是如果我有同一个案例类的两个副本,我将不得不在其余代码的许多地方重复代码逻辑. 如果有办法做到这一点?
当然,给定的代码不起作用,并且像示例一样使用。
谢谢!