Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of unapply in this sample Play framework code (Form mapping)

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.

like image 407
Eran Medan Avatar asked Jan 29 '13 22:01

Eran Medan


2 Answers

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.

like image 115
gourlaysama Avatar answered Dec 08 '22 13:12

gourlaysama


You should learn what are apply/unapply in the Scala context, because it's not specific to Play2/forms.

  • A Tour of Scala: Extractor Objects
  • Scala extractors

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.

like image 45
Julien Lafont Avatar answered Dec 08 '22 13:12

Julien Lafont