Created
July 21, 2011 12:16
-
-
Save jonifreeman/1097071 to your computer and use it in GitHub Desktop.
Elvis loves Options
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
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