Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Option have a fold method?

I wonder why scala.Option doesn't have a method fold like this defined:

fold(ifSome: A => B , ifNone: => B)

equivalent to

map(ifSome).getOrElse(ifNone)

Is there no better than using map + getOrElse?

like image 391
soc Avatar asked Mar 16 '11 15:03

soc


2 Answers

I personally find methods like cata that take two closures as arguments are often overdoing it. Do you really gain in readability over map + getOrElse? Think of a newcomer to your code: What will they make of

opt cata { x => x + 1, 0 }

Do you really think this is clearer than

opt map { x => x + 1 } getOrElse 0

In fact I would argue that neither is preferable over the good old

opt match {
  case Some(x) => x + 1
  case None => 0
}

As always, there's a limit where additional abstraction does not give you benefits and turns counter-productive.

like image 124
Martin Odersky Avatar answered Nov 05 '22 06:11

Martin Odersky


It was finally added in Scala 2.10, with the signature fold[B](ifEmpty: => B)(f: A => B): B.

Unfortunately, this has a common negative consequence: B is inferred for calls based only on the ifEmpty argument, which is in practice often more narrow. E.g. (a correct version is already in the standard library, this is just for demonstration)

 def toList[A](x: Option[A]) = x.fold(Nil)(_ :: Nil)

Scala will infer B to be Nil.type instead of desired List[A] and complain about f not returning Nil.type. Instead, you need one of

 x.fold[List[A]](Nil)(_ :: Nil)
 x.fold(Nil: List[A])(_ :: Nil)

This makes fold not quite equivalent to corresponding match.

like image 41
Alexey Romanov Avatar answered Nov 05 '22 07:11

Alexey Romanov