Skip to content

Instantly share code, notes, and snippets.

@neilchaudhuri
Created March 13, 2019 16:34
Show Gist options
  • Save neilchaudhuri/0faef521f6bb22d32ef75b1c041b6b62 to your computer and use it in GitHub Desktop.
Save neilchaudhuri/0faef521f6bb22d32ef75b1c041b6b62 to your computer and use it in GitHub Desktop.
Idiomatic retrieval of optional values in Scala
case class Student(name: String, house: String)
def findStudent(key: Int): Option[Student] = {
val students = Map(
1 -> Student("Harry Potter", "Hogwarts"),
3 -> Student("Draco Malfoy", "Slytherin")
)
students.get(key)
}
findStudent(3)
.map(s => s"The student's name is ${s.name}")
.getOrElse("Back to Hogwarts")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment