Thinking of Option as List

At the beginning it felt strange to me to use map and flatMap on an Option. But it makes a lot of sense because an Option is just a List which can be empty or just contains one element.

The Option class (Scaladoc) even provides a method to convert an Option to a List:

scala> None.toList
res10: List[Nothing] = List()

scala> Some(3).toList
res11: List[Int] = List(3)

Using map on the Option and then convert to List:

scala> def double(x:Int):Int = 2*x
double: (x: Int)Int

scala> Some(3).map(double).toList
res12: List[Int] = List(6)

Converting to List and then using map on the Option

scala> Some(3).toList.map(double)
res13: List[Int] = List(6)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s