cool breeze
cool breeze

Reputation: 4811

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)
o.map(o => println(o))
>> 1

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

Upvotes: 0

Views: 952

Answers (4)

mfirry
mfirry

Reputation: 3692

I think one should really just follow function signatures.

In this case it can be found here.

It says def flatMap[B](f: (A) ⇒ Option[B]): Option[B]

But the f you're passing has a different signature. Specifically def println(x: Any): Unit

Upvotes: 1

pedrorijo91
pedrorijo91

Reputation: 7845

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 :)

Upvotes: 2

Chris Martin
Chris Martin

Reputation: 30736

I guess the fact that flatMap requires an Option, the reasoning behind it.

This is not really a question that one asks about highly polymorphic functions. It is what it is, that's just the definition of flatMap on Option.

All of these flatMap methods in the Scala API are consistent in that they correspond roughly to the Haskell function (>>=) :: m a -> (a -> m b) -> m b in Control.Monad.

There are methods that do the thing you want (foreach), but they're different methods with different names and different types.

Upvotes: 2

Martin Seeler
Martin Seeler

Reputation: 6982

Because println returns Unit and not a new instance of Option[T]. Flatmap is used to transform a value (if present) and map it to a new Option[T].

What you are doing with println can be accomplished with:

o.foreach(println)

Upvotes: 1

Related Questions