When reducing a collection to a single value, prefer
reduceOption
toreduce
.
Some collections are empty, and reduce
deals with them by throwing an exception:
Seq.empty[Int].reduce(_ + _)
// java.lang.UnsupportedOperationException: empty.reduceLeft
// at scala.collection.LinearSeqOptimized.reduceLeft(LinearSeqOptimized.scala:139)
// at scala.collection.LinearSeqOptimized.reduceLeft$(LinearSeqOptimized.scala:138)
// at scala.collection.immutable.List.reduceLeft(List.scala:89)
// at scala.collection.TraversableOnce.reduce(TraversableOnce.scala:211)
// at scala.collection.TraversableOnce.reduce$(TraversableOnce.scala:211)
// at scala.collection.AbstractTraversable.reduce(Traversable.scala:108)
// at repl.Session$App$$anonfun$1.apply$mcI$sp(traversable_reduce.md:9)
// at repl.Session$App$$anonfun$1.apply(traversable_reduce.md:9)
// at repl.Session$App$$anonfun$1.apply(traversable_reduce.md:9)
reduceOption
is a safer alternative, since it encodes the possibility of the empty list in its return type:
Seq(1, 2, 3).reduceOption(_ + _)
// res0: Option[Int] = Some(6)
Seq.empty[Int].reduceOption(_ + _)
// res1: Option[Int] = None
Linter | Rule |
---|---|
WartRemover |