Skip to content

Instantly share code, notes, and snippets.

@jonifreeman
Created July 21, 2011 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonifreeman/1097071 to your computer and use it in GitHub Desktop.
Save jonifreeman/1097071 to your computer and use it in GitHub Desktop.
Elvis loves Options
implicit def elvisSyntax[A](o: Option[A]) = new {
def ?[B](f: A => Option[B]) = o flatMap f
def :?[B](f: A => B) = o map f
def ??(default: => A) = o getOrElse default
}
case class Head(name: String)
case class Department(head: Option[Head])
case class Employee(department: Option[Department])
scala> val bob: Option[Employee] = None
scala> val alice: Option[Employee] = Some(Employee(Some(Department(Some(Head("foo"))))))
scala> (bob ? (_.department) ? (_.head) :? (_.name)) ?? "no name"
res6: String = no name
scala> (alice ? (_.department) ? (_.head) :? (_.name)) ?? "no name"
res7: String = foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment