more elegant way to write if( list.nonEmpty) Some(list.max) else None?

Viewed 8790

List.max returns the "largest" element of a list based on some ordering... But if the list is empty you'll get a java.lang.UnsupportedOperationException: empty.max exception. I don't really like littering code with if statements or matches or whatever. I want something like headOption for max, but I'm not seeing such a method. What's the most elegant way to get the equivalent of list.maxOption?

5 Answers

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

Another formulation would be

list.headOption.map(_ => list.max)
Related