Options are great because they allow you to circumvent the $1 billion bug (Hoare).
Several posts discuss the great values of Options. It was Graham Tackley who really made me click when he presented Options as collections with zero or one elements in it.
Yesterday I was trying to make good use of this idea, and came with the problem of how retain only the elements that actually contain a value. Since you cannot call get on a None for obvious reasons, there must be an easy way to retrieve only the values.
Here's what i found:
I've transformed a List[Option[String]] with possible Nones in it, to a List[String].
How about this then?
Which is basically doing the operation that I've just done before, call flatMap(_.toList)
This makes passing around options a really valuable thing, because you have safety in your operations with minimal effort.
Very useful Scala Option cheatlist by Tony Morris
No comments:
Post a Comment