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?
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?
If you are sure the list has a zero or one elements you can do this:
option.flatMap(_ => list.headOption)
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
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
?