0

When I try

Some(1).flatMap(_ => List(2))

I get

 error: type mismatch;
 found   : List[Int]
 required: Option[?]

But doing Some(1).map(_ => List(2)).flatten works. How come I get a compile error in the first case?

Garrett Hall
  • 27,772
  • 10
  • 56
  • 73

3 Answers3

5

If you are sure the list has a zero or one elements you can do this:

option.flatMap(_ => list.headOption)
EECOLOR
  • 11,034
  • 3
  • 38
  • 72
4

You can't do this, because the type system forbids this. The type of Option.flatMap is

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

So your function must return an Option type, not a List type.

If you want to convert to a different type, you have to use .map(...).flatten

stefan.schwetschke
  • 8,596
  • 1
  • 22
  • 29
3

Not to say it doesn't work on other Scala versions, but it doesn't work for me:

scala> Some(1).map(_ => List(2)).flatten
<console>:8: error: Cannot prove that List[Int] <:< Option[B].
              Some(1).map(_ => List(2)).flatten
                                        ^

More importantly, what would be the result of Some("abc").flatMap(s => s.toList), or its equivalent Some(List('a','b','c')).flatten?

Daniel C. Sobral
  • 284,820
  • 82
  • 479
  • 670