more elegant way to write if( list.nonEmpty) Some(list.max) else None?
You can convert a Try into an Option:
Try(empty.max).toOption
You can also use reduceOption (as given in scala - Min/max with Option[T] for possibly empty Seq?):
l.reduceOption(_ max _)
Or write your own:
implicit class WithMaxOption[T: Ordering](self: Seq[T]) {
def maxOption() = if(self.isEmpty) None else Some(self.max)
}
List(1,2,3).maxOption // Some(3)
List[Int]().maxOption // None
Starting in Scala 2.13
, minOption
/maxOption
are now part of the standard library:
List(34, 11, 98, 56, 43).maxOption // Option[Int] = Some(98)
List[Int]().maxOption // Option[Int] = None