Created
June 28, 2014 16:19
-
-
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]`
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
// 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