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 . , .