Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kodaka/7c994c44f0d756f55c63db5e6c5089c9 to your computer and use it in GitHub Desktop.
Save kodaka/7c994c44f0d756f55c63db5e6c5089c9 to your computer and use it in GitHub Desktop.
title date tags
Safe Max/Min for Empty List in Scala
2019-06-28 19:30:00 +0900
scala

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment