The conversion from for ... yield
comprehension to map
/flatMap
method calls is done by the compiler. It's not required that the Option
is an Iterable
; the only thing necessary in this case is Option
having map
/ flatMap
methods:
flatMap
if there are more->
calls after it in the samefor
blockmap
if it's the last one
We can create our own MyOption
class like this:
case class MyOption[+T](value: T) {
def flatMap[A](f: T => MyOption[A]): MyOption[A] = f(value)
def map[A](f: T => A): MyOption[A] = MyOption(f(value))
override def toString = s"Some($value)"
}
Then:
val result = for {
a <- MyOption("one")
b <- MyOption("two")
} yield a + "," + b
println(result)
// prints: Some(one,two)