Scala Play表单验证:一个案例类使用不同的表单-可以吗? [英] Scala Play form validation: different forms for one case class - is it possible?
问题描述
我正在寻找一种对一个案例类使用两种不同形式的方法.我试图用其他构造函数来做到这一点,但是失败了.看一下代码片段:
I'm looking for a way to use two different forms for one case class. I was trying to do that with additional constructor, but failed with that. Look at the code snippet:
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(新旧API),但是如果我要拥有同一个case类的两个副本,那么我将不得不在其余的许多地方重复编写代码逻辑代码.如果有办法做到这一点?
What I'm trying to do is to support two API's (new and old one), but if I will have two copies of the same case class, I will have to make code logic duplicates in many many places in the rest of the code. If there is a way to do that?
当然给定的代码不起作用,并且像一个例子一样使用.
Of course given code doesn't work and is used like an example.
谢谢!
推荐答案
您可以尝试将方法applyOld
和unapplyOld
添加到伴随对象,如下所示:
You could try to add methods applyOld
and unapplyOld
to companion object like this:
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) => User
和User => Option[(String, String, Option[Int], String)]
,您可以将它们放置在任意位置.例如,您可以使用方法apply
和unapply
创建对象UserOld
.
You just need methods (String, String, Option[Int], String) => User
and User => Option[(String, String, Option[Int], String)]
, you could place them anywhere you like. For instance you could create object UserOld
with methods apply
and 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))
这篇关于Scala Play表单验证:一个案例类使用不同的表单-可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!