Uncategorized

Options

Options allow us to protect against NullPointerException exceptions.
Option[A] is a container for an optional value of type A. If the value of type A is present, the Option[A] is an instance of Some[A], containing the present value of type A. If the value is absent, the Option[A] is the object None.
For example:
def track(user: Option[User]) = match {
     case Some(u) => Tracker.track(u.id)
     case None => Tracker.track(GUEST)
}
More compact way:
Tracker.track(user map (_.id) getOrElse GUEST)
They can accept filters (conditions) as well:
def track(user: Option[User]) = match {
     case Some(u) if u.canTrack => Tracker.track(u.id)
     case _ => Tracker.track(GUEST)
}
More compact way:
Tracker.track(user filter (_.canTrack) map (_.id) getOrElse GUEST)
More robust:
def track(user: Option[User]) = match {
     case Some(u) if u.canTrack => Tracker.track(u.id)
     case None => Tracker.track(GUEST)
     case _ =>
}
More compact way:
if (user forall (_.canTrack))
     Tracker.track(user map (_.id) getOrElse GUEST)
Advertisements