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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s