Skip to content

Instantly share code, notes, and snippets.

@gideondk
Last active December 16, 2015 17:49
Show Gist options
  • Save gideondk/5472955 to your computer and use it in GitHub Desktop.
Save gideondk/5472955 to your computer and use it in GitHub Desktop.
/* Null based */
def fetchUser(userId: String): User = db.user.fetch(userId)
def fetchOrganization(organizationId: String): Organization = db.organization.fetch(organizationId)
def fetchCase(caseId: String): Case = db.case.fetch(caseId)
def fetchCasesForUser(userId: String): List[Case] = {
val user = fetchUser(userId)
if (user != null) {
val organization = fetchOrganization(user)
if (organization != null) {
organization.caseIds.map(x => fetchCase(x)).filter(_ != null)
} else List[Case]()
} else List[Case]()
}
/* Option based */
def fetchUser(userId: String): Option[User] = db.user.fetch(userId)
def fetchOrganization(organizationId: String): Option[Organization] = db.organization.fetch(organizationId)
def fetchCase(caseId: String): Option[Case] = db.case.fetch(caseId)
def fetchCasesForUser(userId: String): Option[List[Case]] = for {
user <- fetchUser(userId)
org <- fetchOrganization(user.organizationId)
} yield org.caseIds.flatMap(x => fetchCase(x))
@larsrh
Copy link

larsrh commented Apr 27, 2013

The yield part can be expressed more succinctly as org.caseIds flatMap fetchCase. Also, the method returns Option[List[Case]].

Good example, though.

@gideondk
Copy link
Author

You're right, leaving the explicit function notations for the non-Scala programmers among us...

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