i knew this question might be dumb.
I just found myself have difficulty understanding the fold
definition from Scala Option
link.
Can anyone help me to understand the definition part? final def fold[B](ifEmpty: => B)(f: (A) => B): B
What does (ifEmpty: => B)
mean, does the ifEmpty
here represents a function? What does the right part => B
represent? Does it represent a function without any parameter? Should that be () => B
?
There is quite a lot of going on in definition of
final def fold[B](ifEmpty: => B)(f: (A) => B): B
We have
ifEmpty: => B
. This is indeed similar to () => B
and means ifEmpty
is not evaluated until used (if ever) inside the method body.(ifEmpty: => B)(f: (A) => B)
which helps type inference because Scala type inference works per list. This means we do not have to explicitly provide [B]
type parameter at call-site.A
and B
make the method polymorphicfinal
prevents the method from being overridenfold
is a higher-order method because it accepts argument of function type (A) => B