cool breeze cool breeze - 14 days ago 4
Scala Question

Flatmapping on an option value

Why exactly does the flatMap not work in this case, can someone please detail what is going on.

val o: Option[Int] = Some(1) => println(o))
>> 1

o.flatMap(o => println(o))
>><console>:13: error: type mismatch;
found : Unit
required: Option[?]
o.flatMap(o => println(o))


basically, and not trying to be 100% correct, but more trying to give a nice overview, you have:

  • collections (like Lists and Sets) and some other containers (like Option) have a map method that is applied to the elements inside (in case of the list it transforms every element using the function you provide. in case of the Option, is transforms the only element using the function you provide)
  • collections and (some) containers also have a flat/flatten method which flats a nested collection (List of Lists to a List with all elements, or Option of Option to Option)
  • flatmap is a map followed by a flatten. in order to use it, your map function/transformation must return a collection/container

while not 100% correct, it should be enough to get you started and understand :)