this is a copy from https://github.com/scala/bug/issues/11232 where it was suggested to raise the issue here. I choose Scala Platform due to lack of better fitting categories. This issue describes unexpected behaviour, i.e. I regard it as a bug, however scala/bug wants more precise bug descriptions. Maybe adding a “pre-bug” category to scala contributors?
Dear Scala developers,
I just stumbled upon the standard case that Option and Iterable might be hard to intertwine in a scala for loop. See for instance this stackoverflow question
I tried to fix this by just overloading flatMap
with a version which should work, however it doesn’t.
When I run the following in scala 2.11.12 REPL
implicit class OptionFlatMapIterable[A](o: Option[A]){
def flatMap[B](f: A => Iterable[B]): Iterable[B] = if (o.isEmpty) Seq.empty else f(o.get)
def flatMap2[B](f: A => Option[B]): Option[B] = o.flatMap(f)
def flatMap2[B](f: A => Iterable[B]): Iterable[B] = if (o.isEmpty) Seq.empty else f(o.get)
}
Some(42).flatMap2{ (o: Int) =>
Seq(o, o + 1, o + 3).map{ (i: Int) =>
(i,i)
}
}
Some(42).flatMap{ (o: Int) =>
Seq(o, o + 1, o + 3).map{ (i: Int) =>
(i,i)
}
}
for{
o <- Some(42)
i <- Seq(o, o + 1, o + 3)
} yield (o, i)
I get the following outputs
res0: Iterable[(Int, Int)] = List((42,42), (43,43), (45,45))
<console>:14: error: type mismatch;
found : Seq[(Int, Int)]
required: Option[?]
Seq(o, o + 1, o + 3).map{ (i: Int) =>
^
<console>:15: error: type mismatch;
found : Seq[(Int, Int)]
required: Option[?]
i <- Seq(o, o + 1, o + 3)
^
As you can see it perfectly works when using my dummy flatMap2
, but fails for flatMap
itself.
If this would work, it could massively simplify the support of complex flatMap
chainings and hence complex for
loops with different Monads intermixing a base Iterable
Monad.
please, anyone who can help?