Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala map method on option

Tags:

scala

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?

like image 770
vivman Avatar asked Aug 10 '16 07:08

vivman


2 Answers

Sometimes it's more convenient to use fold instead of mapping Options. 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.

like image 78
Vladimir Salin Avatar answered Oct 21 '22 14:10

Vladimir Salin


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.

like image 45
Luka Jacobowitz Avatar answered Oct 21 '22 13:10

Luka Jacobowitz