Skip to content

Instantly share code, notes, and snippets.

@metasim
Created June 28, 2014 16:19
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 metasim/742a3a44e2d5a0480b48 to your computer and use it in GitHub Desktop.
Save metasim/742a3a44e2d5a0480b48 to your computer and use it in GitHub Desktop.
Explanatory example showing how `Option[T]` is much more powerful than just `null.asInstanceOf[T]`
// Comparison of using `null` vs `None` to represetn NAs
val csvtext = "1,4,5,6,,9,12"
val tokens = csvtext.split(",").toList
// Null NA Approach
val nullNAs = tokens.map(t => if(t.isEmpty) null else t)
val numFromNulled = for {
t <- nullNAs
num = if(t == null) null else t.toInt
} yield(num)
val numFromNulledFiltered = numFromNulled.filter(_ != null)
// Option NA Approach
val optionNAs = tokens.map(t => if(t.isEmpty) None else Some(t))
val numFromOptioned = for {
optioned <- optionNAs
num = if(optioned.isEmpty) None else Some(optioned.get.toInt)
} yield(num)
val numFromOptionedFiltered = numFromOptioned.filter(_.nonEmpty).flatten
val tightNumFromOptioned = optionNAs.flatMap(_.map(_.toInt))
val forNumFromOptioned = for {
maybeNA <- optionNAs
t <- maybeNA
} yield(t.toInt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment