Created
March 13, 2019 16:34
-
-
Save neilchaudhuri/0faef521f6bb22d32ef75b1c041b6b62 to your computer and use it in GitHub Desktop.
Idiomatic retrieval of optional values in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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