Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

for







Introduction to for Loops

  • Overview: Scala's for loop is a control structure for iterating over elements in collections, such as lists, arrays, and more. It's more powerful and flexible than traditional for loops found in many other languages, supporting advanced iteration patterns and for-comprehensions.
  • Syntax:
    for (item <- collection) {
      // operation using item
    }
    
  • Key Points:
    • The loop variable item takes on each value in the collection one by one.
    • Scala's for can also iterate through multiple collections simultaneously or nest iterations within one another.
    • The arrow <- is used to denote extraction of each element from the collection.







Filtering with Guards

  • Overview: Guards are conditions within for loops that allow filtering elements of the collection being iterated over.
  • Syntax:
    for (item <- collection if condition) {
      // operation using item
    }
    
  • Example:
    for (num <- 1 to 10 if num % 2 == 0) {
      println(num) // Prints even numbers between 1 and 10
    }
    







for Comprehensions

  • Overview: for comprehensions are a powerful feature in Scala that allow for filtering, mapping, and flatMapping operations on collections, all within the for loop syntax. They are particularly useful for working with collections in a more functional style.
  • Syntax:
    val result = for (item <- collection if condition) yield {
      // transform item
    }
    
  • Example:
    val squares = for (num <- 1 to 5) yield num * num
    // squares: IndexedSeq[Int] = Vector(1, 4, 9, 16, 25)
    







Nested for Loops

  • Overview: Scala supports nesting for loops within each other to iterate over multiple dimensions or perform complex iteration patterns.
  • Syntax:
    for (item1 <- collection1; item2 <- collection2) {
      // operation using item1 and item2
    }
    
  • Example:
    for (x <- 1 to 3; y <- 1 to 3) {
      println(s"($x, $y)")
    }
    







Best Practices

  • Use Descriptive Names: Choose descriptive names for loop variables to make your code more readable and maintainable.
  • Prefer for Comprehensions for Complex Logic: Leverage for comprehensions to simplify complex collection manipulations, improving readability.
  • Immutable Collections: When generating new collections with for comprehensions, take advantage of Scala's immutable collections to promote functional programming principles.
  • Performance Considerations: While for loops are convenient and powerful, be mindful of their performance impact, especially with large collections or complex nested loops.