With the current implementation of Option.fold
(as seen when looking in Scala 3.1)
@inline final def fold[B](ifEmpty: => B)(f: A => B): B =
if (isEmpty) ifEmpty else f(this.get)
the following (silly) example is not tail recursive:
def recurse(in: Int): Int =
Option(1).fold(1)(next => recurse(in + 1))
If we would change the standard library to implement Option.fold
like this:
inline final def fold[B](inline ifEmpty: B)(inline f: A => B): B =
if (isEmpty) ifEmpty else f(this.get)
then the same example is tailrec. Is this something that has a chance to be accepted in the scala/scala-library-next repository? I’m willing to create a PR, but first would like to check whether it has chances to be accepted…
See also Why can’t Option.fold be used tail recursively in Scala? - Stack Overflow