Skip to content

Instantly share code, notes, and snippets.

@drstevens
Last active December 15, 2015 19:49
Show Gist options
  • Save drstevens/5314012 to your computer and use it in GitHub Desktop.
Save drstevens/5314012 to your computer and use it in GitHub Desktop.
This example demonstrates benefits of using fold/cata instead of map and getOrElse on Option[T]. There are, of course, occasions when pattern matching is preferable as well.
Welcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_15).
Type in expressions to have them evaluated.
Type :help for more information.
scala> val opt: Option[Int] = Some(10)
opt: Option[Int] = Some(10)
scala> val typeCheckFail = opt map (_ + "2") getOrElse (3)
typeCheckFail: Any = 102
scala> val typeCheckWin = opt.fold(3)(_ + "2")
<console>:8: error: type mismatch;
found : String
required: Int
val typeCheckWin = opt.fold(3)(_ + "2")
scala> val typeCheckFailAgain = opt match {
| case Some(x) => x + "2"
| case None => 3
| }
typeCheckFailAgain: Any = 102
scala> val patternMatchOops = opt match {
| case Some(x) => x + "2" //At least I get a warning here
| }
<console>:8: warning: match may not be exhaustive.
It would fail on the following input: None
val patternMatchOops = opt match {
^
patternMatchOops: String = 102
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment