Min/max with Option[T] for possibly empty Seq?
scala, scala-collections
Solution
Starting `Scala 2.13`, `minByOption`/`maxByOption` is now part of the standard library and returns `None` if the sequence is empty:
seq.minByOption(_.something)
List((3, 'a'), (1, 'b'), (5, 'c')).minByOption(_._1) // Option[(Int, Char)] = Some((1,b))
List[(Int, Char)]().minByOption(_._1) // Option[(Int, Char)] = None
Problem
I'm doing a bit of Scala gymnastics where I have `Seq[T]` in which I try to find the "smallest" element. This is what I do right now: ``` val leastOrNone = seq.reduceOption { (best, current) => if (current.something < best.something) current else best } ``` It works fine, but I'm not quite satisfied - it's a bit long for such a simple thing, and I don't care much for "if"s. Using `minBy` would be much more elegant: ``` val least = seq.minBy(_.something) ``` ... but `min` and `minBy` throw exceptions when the sequence is empty. Is there an idiomatic, more elegant way of finding the smallest element of a possibly empty list as an `Option`?