0

i knew this question might be dumb.

I just found myself have difficulty understanding the fold definition from Scala Optionlink.

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?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
KevinZhou
  • 447
  • 4
  • 10
  • 1
    This is a duplicate, but before they close this question let me answer it. `=> B` is a [**by name parameter**](https://docs.scala-lang.org/tour/by-name-parameters.html), which basically means the same as `() => B` but has some syntactic and semantic differences. It is also known as lazy parameters because it is only evaluated if used. In this case, it makes sense. The idea of `fold` on option is to be a shortcut of `opt.map(f).getOrElse(default) === opt.fold(ifEmpty = default)(f)` So, if you have a value you map it, if not you give the value to return, which is not always necessary, thus lazy. – Luis Miguel Mejía Suárez Apr 20 '20 at 22:37

1 Answers1

2

There is quite a lot of going on in definition of

final def fold[B](ifEmpty: => B)(f: (A) => B): B

We have

  • by-name parameter ifEmpty: => B. This is indeed similar to () => B and means ifEmpty is not evaluated until used (if ever) inside the method body.
  • multiple parameter lists (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.
  • type parameters A and B make the method polymorphic
  • final prevents the method from being overriden
  • fold is a higher-order method because it accepts argument of function type (A) => B
Mario Galic
  • 47,285
  • 6
  • 56
  • 98