fold option
If you look at the signature of the Option fold function, it takes two parameters:
def fold[B](ifEmpty: => B)(f: A => B): B
What it does is, it applies f to the Option value if it is not empty. If Option empty, it simply returns ifEmpty output (this is a termination condition for recursion).
So, in your case, i => i.toLong :: factors(n / i) represents f , which will be evaluated if Option not empty. While List(n) is a termination condition.
fold used for collection / iterators
The other fold that you take to get the collection amount comes from TraversableOnce and has a signature like:
def foldLeft[B](z: B)(op: (B, A) => B): B
Here z is the starting value (suppose that the sum of the sum is 0 ) and op is the associative binary operator that is applied to z , and each collection value is from left to right.
Thus, both fold are distinguished by their implementation.
source share