I'm not an FP expert, but I understand that, generally speaking, completely converts the contents of a type to another type, given the recursive structure of the original type, if applicable. Usually you get the result of one type for each case of the original type.
List most famous. I always thought of fold as in the main for loop with the battery, but you can also consider it as two cases: one for the Nil case and one for the Cons case. Since the actual type of List is recursive, it should be fold .
The Scala standard library defines fold on Option , as well as the signature fold[B](ifEmpty: ⇒ B)(f: (A) ⇒ B): B In this case, since the type is not recursive, fold really just two functions for two cases.
Your case is very similar to Option . A type is not recursive, so fold basically boils down to mapping all cases of its state to a single type of output.
Note that fold differs from map and flatMap in that the last two preserve the original type, but change its contents.
source share