Skip to content

Instantly share code, notes, and snippets.

@eboto
Created October 17, 2013 04:54
Show Gist options
  • Save eboto/7019351 to your computer and use it in GitHub Desktop.
Save eboto/7019351 to your computer and use it in GitHub Desktop.
Some Either and Option fun
case class User(id: Long, name: String)
case class ZipCode(userId: Long, zipCode: String)
trait Error {
def message: String
}
case class UserError(message: String) extends Error
case class ZipError(message: String) extends Error
/*
Option[T]
| \
None Some[T](x: T)
*/
object UserDB {
def findById(id: Long): Either[UserError, User] = {
Left(UserError("No user!"))
}
}
object ZipCodeDB {
def findByUserId(id: Long): Either[ZipError, ZipCode] = {
Left(ZipError("No Zip!"))
}
}
object Main {
def main(args: Array[String]): Unit = {
println("")
println("Hello!")
val errorOrGreeting: Either[Error, String] = for {
user <- UserDB.findById(1L).right
zip <- ZipCodeDB.findByUserId(user.id).right
} yield {
s"Welcome, $user!"
}
val finalGreeting: String = errorOrGreeting.fold(
failure => s"Oops! Encountered $failure",
success => success
)
println(finalGreeting)
/* val maybeGreeting = for {
user <- UserDB.findById(1L)
zipCode <- ZipCodeDB.findByUserId(user.id)
} yield {
s"Hello ${user}. You are from ${zipCode}"
}
*/
/* val maybeUser: Option[User] = UserDB.findById(1L)
val maybeGreeting: Option[String] = for (user <- maybeUser) yield {
s"Hello ${user.name}!"
}
println(maybeGreeting.getOrElse("I don't know who you are"))
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment