Tutorial by Examples

for (x <- 1 to 10) println("Iteration number " + x) This demonstrates iterating a variable, x, from 1 to 10 and doing something with that value. The return type of this for comprehension is Unit.
This demonstrates a filter on a for-loop, and the use of yield to create a 'sequence comprehension': for ( x <- 1 to 10 if x % 2 == 0) yield x The output for this is: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10) A for comprehension is useful when you need to crea...
This shows how you can iterate over multiple variables: for { x <- 1 to 2 y <- 'a' to 'd' } println("(" + x + "," + y + ")") (Note that to here is an infix operator method that returns an inclusive range. See the definition here.) This creates the outp...
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 expre...
This demonstrates how to print each element of a Map val map = Map(1 -> "a", 2 -> "b") for (number <- map) println(number) // prints (1,a), (2,b) for ((key, value) <- map) println(value) // prints a, b This demonstrates how to print each element of a list val l...
for comprehensions in Scala are just syntactic sugar. These comprehensions are implemented using the withFilter, foreach, flatMap and map methods of their subject types. For this reason, only types that have these methods defined can be utilized in a for comprehension. A for comprehension of the fo...

Page 1 of 1