Reputation: 365
I am new to scala, please help me with the below question.
Can we call map method on an Option? (e.g. Option[Int].map()?).
If yes then could you help me with an example?
Upvotes: 14
Views: 34299
Reputation: 3030
Sometimes it's more convenient to use fold
instead of mapping Option
s. Consider the example:
scala> def printSome(some: Option[String]) = some.fold(println("Nothing provided"))(println)
printSome: (some: Option[String])Unit
scala> printSome(Some("Hi there!"))
Hi there!
scala> printSome(None)
Nothing provided
You can easily proceed with the real value inside fold
, e.g. map it or do whatever you want, and you're safe with the default fold option which is triggered on Option#isEmpty
.
Upvotes: 2
Reputation: 23502
Here's a simple example:
val x = Option(5)
val y = x.map(_ + 10)
println(y)
This will result in Some(15)
.
If x
were None
instead, y
would also be None
.
Upvotes: 15
Reputation: 546
Yes:
val someInt = Some (2)
val noneInt:Option[Int] = None
val someIntRes = someInt.map (_ * 2) //Some (4)
val noneIntRes = noneInt.map (_ * 2) //None
See docs
You can view an option as a collection that contains exactly 0 or 1 items. Mapp over the collection gives you a container with the same number of items, with the result of applying the mapping function to every item in the original.
Upvotes: 11