I'm new to Play framework and going over the 2.1 samples, and in the computer-database
example, I've found the following form definition that I don't fully understand.
What is the role of Computer.apply
and Computer.unapply
here?
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)
)
(from controllers/Application.scala
)
EDIT: this seems to be a good resource: https://groups.google.com/forum/?fromgroups=#!topic/play-framework/dxNQ8E81YJs but still not sure I fully get the big picture.
That's a common pattern in Play when you want to bind a form to the fields of a case class (in this case Computer
).
The mapping
method allows you to provide the construction and deconstruction functions that will be called to populate the form and extract data from it.
Since here you want to go to/from Computer
, you need a method that creates a Computer
from parameters, and one that extract parameters from a Computer
, and that's exactly Computer.apply
and Computer.unapply
.
Related example: the mapping example in the Play documentation on forms.
You should learn what are apply/unapply in the Scala context, because it's not specific to 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.
In a nutshell: apply
is used to construct Computer object from parameters. unapply
is used for the opposite case, extract parameters from the Computer object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With