2

我正在寻找一种方法来为一个案例类使用两种不同的形式。我试图用额外的构造函数来做到这一点,但失败了。看代码片段:

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(新的和旧的),但是如果我有同一个案例类的两个副本,我将不得不在其余代码的许多地方重复代码逻辑. 如果有办法做到这一点?

当然,给定的代码不起作用,并且像示例一样使用。

谢谢!

4

2 回答 2

5

您可以尝试像这样添加方法applyOldunapplyOld伴随对象:

case class User(username: String, loginDetails: LoginDetails)
object User {
  def applyOld(username: String, password: String, field3: Option[Int], field4: String) = new User(username, LoginDetails(password, field3, field4))
  def unapplyOld(u: User): Option[(String, String, Option[Int], String)] =
    Some((u.username, u.loginDetails.password,  u.loginDetails.field3,  u.loginDetails.field4))
}

你只需要方法(String, String, Option[Int], String) => UserUser => Option[(String, String, Option[Int], String)]你可以把它们放在你喜欢的任何地方。例如,您可以UserOld使用方法apply和创建对象unapply

用法:

val oldForm = Form(
 mapping(
   "username" -> email,
   "password" -> text,
   "field3" -> optional(number),
   "field4" -> text
 )(User.applyOld)(User.unapplyOld))

val newForm = Form(
     mapping(
       "username" -> email,
       "loginDetails" -> loginDetailsForm.mapping
     )(User.apply)(User.unapply))
于 2013-06-03T12:41:36.910 回答
3

您可以直接在定义表单的地方执行应用/取消应用。然后您不必向案例类添加任何新的构造函数。

val oldForm = Form(
  mapping(
    "username" -> email,
    "password" -> text,
    "field3" -> optional(number),
    "field4" -> text
  )(
    (username, password, field3, field4) =>
      User(username, LoginDetails(password, field3, field4))
  )(
    (user: User) =>
      Option(user.username, user.loginDetails.password, user.loginDetails.field3, user.loginDetails.field4)
  )
)

val newForm = Form(
  mapping(
    "username" -> email,
    "loginDetails" -> loginDetailsForm.mapping
  )(User.apply)(User.unapply))
于 2013-06-03T13:09:55.313 回答