Skip to content

Instantly share code, notes, and snippets.

@sam
Created November 5, 2015 16:20
Show Gist options
  • Save sam/f3c9aca611fb9774b5c2 to your computer and use it in GitHub Desktop.
Save sam/f3c9aca611fb9774b5c2 to your computer and use it in GitHub Desktop.
Example on how to fallback several Options with `orElse` with is a method to create a fallback chain for Options of the same type.
case class PhotoListItem(title: Option[String], filename: Option[String]) {
// Not bad:
def displayTitle(implicit messages: Messages): String = {
(title, filename) match {
case (Some(title), _) => title // So I want the title if present.
case (_, Some(filename)) => filename // Fallback to filename.
case _ => messages("label.titleNotAvailable") // Otherwise return a canned message.
}
}
// But better:
def displayTitle(implicit messages: Messages): String = {
title orElse filename getOrElse messages("label.titleNotAvailable")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment