简体   繁体   中英

Scala map method on option

I am new to scala, please help me with the below question.

Can we call map method on an Option? (eg Option[Int].map()?) .

If yes then could you help me with an example?

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 .

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.

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 , eg map it or do whatever you want, and you're safe with the default fold option which is triggered on Option#isEmpty .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM