I'm referring to this:
http://www.playframework.org/documentation/api/2.0.2/scala/index.html#play.api.data.Form
If you search for a method called fold, it shows a method used for handling the form. Is there a reason why this method is called fold? Given that fold already has a meaning for list like objects, it seems that this name could easily cause confusion.
This is the explanation of {play for scala}: In Scala, fold is often used as the name of a method that collapses (or folds) multiple pos- sible values into a single value. In this case, we’re attempting to fold either a form with validation errors or one that validates correctly into a response.
The
fold
onForm
is pretty close to thefold
on theEither
class in the Scala standard library, which is similarly often used to capture the outcome of a process that could either succeed (in which case you have aRight
containing the result) or fail (in which case you have aLeft
containing an error, or maybe leftover input, etc.). So I'll useEither
as an example here. Just pictureForm[T]
as a kind ofEither[Form[T], T]
if necessary.Fold on collections
We can (very informally) imagine lists as having lots of different "shapes" (empty lists, lists of length one, length two, etc.), and
fold
(orfoldLeft
, in the following example) as a method that collapses any list of the proper type to a single kind of thing, no matter what its shape is:Fold on Either / Form
Similarly we can imagine
Either
as having two shapes (Right
andLeft
), and itsfold
as a method that takes anEither
of either shape and returns a single kind of thing. Say we have the following method for parsing strings as integers and returning anEither
:And the following method that uses
fold
to collapse theEither
:Which we can use like this:
This is all obviously very impressionistic and hand-wavy, but it might help give a more intuitive sense of how the different
fold
methods are fundamentally the same kind of thing. You can see the question I linked in a comment above or the Wikipedia entry on catamorphisms for more detail.