Why is there a fold method for a form in Play 2.0.2?

I mean the following:

http://www.playframework.org/documentation/api/2.0.2/scala/index.html#play.api.data.Form

If you are looking for a method called fold, it shows the method used to process the form. Is there a reason why this method is called fold? Given that folding already matters for list type objects, it seems that this name can easily cause confusion.

+5
source share
2 answers

foldin is Formpretty close to foldthe class Eitherin the Scala standard library, which is often used to capture the results of a process that may be successful (in this case you have Rightone containing the result) or crash (in this case you have Leftone containing the error or maybe remaining input, etc.). Therefore, I will use Eitheras an example. Just portray Form[T]as a view Either[Form[T], T], if necessary.

Add to collection

We can (very informally) present lists as having many different “forms” (empty lists, lists of length one, length two, etc.) and fold(or foldLeft, in the following example) as a method that collapses any list of the corresponding type into one type of thing, regardless of its shape:

scala> def catInts(xs: List[Int]): String = xs.foldLeft("")(_ + _.toString)
catInts: (xs: List[Int])String

scala> catInts(List(1, 2, 3, 4))
res0: String = 1234

scala> catInts(Nil)
res1: String = ""

Add to Either / Form

, , Either (Right Left) fold , Either . , Either:

def parseInt(s: String): Either[String, Int] =
  try Right(s.toInt) catch {
    case _: NumberFormatException => Left(s)
  }

, fold Either:

def toDefault(e: Either[String, Int]): Int = e.fold(_ => 42, identity)

:

scala> toDefault(parseInt("AAARGH!!"))
res2: Int = 42

scala> toDefault(parseInt("123"))
res3: Int = 123

, , -, , fold . , .

+10

{play for scala}: Scala , ( ) . , .

-2

All Articles