Skip to content

Instantly share code, notes, and snippets.

@last-ent
Last active June 7, 2020 23:59
Show Gist options
  • Save last-ent/9554bf80cf98aede3304faa190db2938 to your computer and use it in GitHub Desktop.
Save last-ent/9554bf80cf98aede3304faa190db2938 to your computer and use it in GitHub Desktop.
Code used in my blog post: Introduction to Option Type - https://last-ent.com/posts/introduction-to-option-type/
/*
BASIC EXAMPLE
*/
val hMap0: Map[Int, Int] = Map(1 -> 102, 2 -> 202, 3 -> 302)
hMap0.get(100)
// What should be the value here?
// `100` does not exist in `hMap`
/*
EXTRACTOR FROM OPTION
*/
def getFromOption(opt: Option[String]): String =
"Got Value: " + opt.getOrElse("None")
getFromOption(Some("100")) // "Got Value: 100"
getFromOption(None) // "Got Value: None"
def extractFromOption(opt: Option[String]): String =
opt match {
case None => "Got Value: " + "None"
case Some(value) => "Got Value: " + value
}
extractFromOption(Some("100")) // "Got Value: 100"
extractFromOption(None) // "Got Value: None"
/*
FUNCTIONS FOR WORKING WITHIN CONTEXT
*/
val hMap: Map[Int, Value] =
Map(
1 -> Value(102),
2 -> Value(202),
3 -> Value(302)
)
def getOptionValue(i: Int): Option[Value] = hMap.get(i)
def addTen(i: Value): Value10 = Value10(i.value + 10)
def asString(num: Value10): String =
s"Got Value: ${num.value}"
case class Value(value: Int)
case class Value10(value: Int)
/*
WORKING WITHIN CONTEXT
*/
def mapOpt(i: Int): Option[String] =
getOptionValue(i)
.map(addTen)
.map(asString)
extractFromOption(mapOpt(3)) // "Got Value: 312"
extractFromOption(mapOpt(100)) // "Got Value: None"
def forOpt(i: Int): Option[String] =
for {
value <- hMap.get(i)
val10 <- Option.apply(addTen(value))
str <- Option.apply(asString(val10))
} yield str
extractFromOption(forOpt(3)) // "Got Value: 312"
extractFromOption(forOpt(100)) // "Got Value: None"
def flatMapOpt(i: Int): Option[String] =
getOptionValue(i)
.flatMap(valOpt => Option.apply(addTen(valOpt)))
.flatMap(val10 => Option.apply(asString(val10)))
extractFromOption(flatMapOpt(3)) // "Got Value: 312"
extractFromOption(flatMapOpt(100)) // "Got Value: None"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment