我是 Play 框架的新手,正在浏览 2.1 samples ,并在 computer-database
例如,我发现了以下我不完全理解的表单定义。Computer.apply
的作用是什么?和 Computer.unapply
这里?
val computerForm = Form(
mapping(
"id" -> ignored(NotAssigned:Pk[Long]),
"name" -> nonEmptyText,
"introduced" -> optional(date("yyyy-MM-dd")),
"discontinued" -> optional(date("yyyy-MM-dd")),
"company" -> optional(longNumber)
)(Computer.apply)(Computer.unapply)
)
(来自
controllers/Application.scala
)编辑 :这似乎是一个很好的资源:https://groups.google.com/forum/?fromgroups=#!topic/play-framework/dxNQ8E81YJs但仍然不确定我是否完全了解大局。
最佳答案
您应该了解 Scala 上下文中应用/取消应用的内容,因为它不是特定于 Play2/forms 的。
In the apply method we take the required parameters and return the new instance of class we are interested in where as we do the reverse in unapply- we take the instance and extract out the required information and return them in the form of a tuple.
简而言之:
apply
用于从参数构造计算机对象。 unapply
用于相反的情况,从 Computer 对象中提取参数。
关于scala - 这个示例Play框架代码中unapply有什么用(表单映射),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14593589/