Reputation: 4811
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
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
Reputation: 7845
basically, and not trying to be 100% correct, but more trying to give a nice overview, you have:
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)flat
/flatten
method which flats a nested collection (List of Lists to a List with all elements, or Option of Option to Option)while not 100% correct, it should be enough to get you started and understand :)
Upvotes: 2
Reputation: 30736
I guess the fact that
flatMap
requires anOption
, 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
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