I have difficulty understanding the mechanism using for-compression in Scala. For example, if I have
val x = for {
i <- Option(1)
j <- Option(2)
k <- Option(3)
} yield (i,j,k)
x
is x: Option[(Int, Int, Int)] = Some((1,2,3))
.
However, if at least one of component is None, for example,
val x = for {
i <- Option(1)
j <- Option(2)
k <- None
} yield (i,j,k)
then x
is x: Option[(Int, Int, Nothing)] = None
, while I actually hoped to see something like : x: Option[(Int, Int, Nothing)] = Some((1,2,None))
.
I have checked the FAQ from Scala official documentation where it is specifically stated that for-comprehension
is a combination of flatmap
and map
. But I still have difficulty understanding that x
is None
.
I think I missed some important concepts on flatmap
and map
difference.