title | date | tags | |
---|---|---|---|
Safe Max/Min for Empty List in Scala |
2019-06-28 19:30:00 +0900 |
|
List (Seq) in Scala has max
method
but it is failed if the list is empty.
Try something like those:
val nums = List[Int].empty
val maxNum = nums.max // booom! you are dead
val maybeMaxNumA = nums.headOption(_ => nums.max) // yeah!
val maybeMaxNumB = nums.reduceOption(_ max _) // yeah!
You know, it works for min
too.