Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 230
nairbv Avatar asked Dec 09 '13 22:12

nairbv


2 Answers

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 _)
like image 145
Rob Napier Avatar answered Sep 21 '22 06:09

Rob Napier


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
like image 44
dhg Avatar answered Sep 23 '22 06:09

dhg