Scala Language Monadic for comprehensions


If you have several objects of monadic types, we can achieve combinations of the values using a 'for comprehension':

for {
   x <- Option(1)
   y <- Option("b")
   z <- List(3, 4)
} {
    // Now we can use the x, y, z variables
    println(x, y, z)
    x  // the last expression is *not* the output of the block in this case!

// This prints
// (1, "b", 3)
// (1, "b", 4)

The return type of this block is Unit.

If the objects are of the same monadic type M (e.g. Option) then using yield will return an object of type M instead of Unit.

val a = for {
   x <- Option(1)
   y <- Option("b")
} yield {
    // Now we can use the x, y variables
    println(x, y)
    // whatever is at the end of the block is the output
    (7 * x, y)

// This prints:
// (1, "b")
// The val `a` is set:
// a: Option[(Int, String)] = Some((7,b))

Note that the yield keyword cannot be used in the original example, where there is a mix of monadic types (Option and List). Trying to do so will yield a compile-time type mismatch error.