Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

For Loop in Scala

In Scala, the for loop is a versatile control structure that allows iteration over a range of values, collections, and even allows for comprehensions with filtering. Let's delve into the various ways you can use the for loop in Scala:

1. Looping Over a Range

The simplest form of a for loop iterates over a range of numbers:

for (i <- 1 to 5) {
  println(i)  // Prints numbers from 1 to 5
}

for (i <- 1 until 5) {
  println(i)  // Prints numbers from 1 to 4
}

2. Looping Over Collections

You can iterate over elements of a collection like a List, Array, Set, etc.:

val fruits = List("apple", "banana", "cherry")

for (fruit <- fruits) {
  println(fruit)
}

3. Using Guards (Conditions)

You can add conditions to your for loop with the if keyword:

for (i <- 1 to 10 if i % 2 == 0) {
  println(i)  // Prints even numbers between 1 and 10
}

4. Nested Loops

You can nest multiple for loops to iterate over multiple collections or ranges:

for {
  i <- 1 to 3
  j <- 1 to 3
} {
  println(s"i = $i, j = $j")
}

5. Yielding Values: For Comprehensions

The for loop can also produce values, which is known as a for-comprehension:

val numbers = List(1, 2, 3, 4, 5)
val squares = for (n <- numbers) yield n * n
println(squares)  // List(1, 4, 9, 16, 25)

6. Multiple Generators and Filters

In a for-comprehension, you can use multiple generators and filters:

val pairs = for {
  i <- 1 to 3
  j <- 1 to 3 if i != j
} yield (i, j)

println(pairs)  // Vector((1,2), (1,3), (2,1), (2,3), (3,1), (3,2))

7. Using Pattern Matching

You can combine pattern matching with for loops:

val listOfTuples = List((1, "one"), (2, "two"), (3, "three"))

for ((number, word) <- listOfTuples) {
  println(s"Number: $number, Word: $word")
}

The for loop in Scala provides a concise and expressive way to handle iterations and comprehensions. Its versatility in handling different data types, nested iterations, guards, and pattern matching makes it a powerful feature in Scala.

  1. Using for loops for iteration in Scala:

    • Description: The basic for loop in Scala is used for iteration over a sequence of values.
    • Code Example:
      for (i <- 1 to 5) {
        println(s"Iteration $i")
      }
      
  2. Range-based for loops in Scala:

    • Description: Range-based for loops use the to or until methods to define a range of values.
    • Code Example:
      for (i <- 1 to 5) {
        println(s"Value: $i")
      }
      
  3. For loop with conditions in Scala:

    • Description: Conditions can be added to for loops for selective iteration.
    • Code Example:
      for (i <- 1 to 10 if i % 2 == 0) {
        println(s"Even Value: $i")
      }
      
  4. Nested for loops in Scala:

    • Description: Multiple generators in a for loop create nested loops.
    • Code Example:
      for (i <- 1 to 3; j <- 1 to 3) {
        println(s"($i, $j)")
      }
      
  5. Yield keyword in Scala for loops:

    • Description: The yield keyword transforms a for loop into a generator, creating a new collection.
    • Code Example:
      val squares: Seq[Int] = for (i <- 1 to 5) yield i * i
      
  6. Comprehensions and generators in Scala for loops:

    • Description: Comprehensions combine multiple generators and conditions in a concise form.
    • Code Example:
      val pairs: Seq[(Int, Int)] = for {
        i <- 1 to 3
        j <- 1 to 2 if i != j
      } yield (i, j)
      
  7. For loop vs. foreach in Scala:

    • Description: For loop and foreach are distinct constructs. For loops are expressions with a yield, while foreach is a method for iterating over collections.
    • Code Example (For Loop):
      val squares: Seq[Int] = for (i <- 1 to 5) yield i * i
      
    • Code Example (Foreach):
      val numbers: Seq[Int] = Seq(1, 2, 3, 4, 5)
      numbers.foreach(n => println(n))
      
  8. For loop with collections in Scala:

    • Description: For loops can iterate over collections directly without using generators.
    • Code Example:
      val colors: Seq[String] = Seq("Red", "Green", "Blue")
      for (color <- colors) {
        println(s"Color: $color")
      }
      
  9. Parallel collections and for loops in Scala:

    • Description: Parallel collections enable parallel processing of elements in a for loop for improved performance.
    • Code Example:
      val numbers: ParSeq[Int] = (1 to 10).par
      for (n <- numbers) {
        println(s"Number: $n")
      }
      
  10. For loop with yield and map in Scala:

    • Description: Combining for loop with yield and map can transform and process collections.
    • Code Example:
      val numbers: Seq[Int] = Seq(1, 2, 3, 4, 5)
      val squaredDoubled: Seq[Int] = for (n <- numbers) yield n * n * 2
      
  11. Looping over arrays and lists in Scala:

    • Description: Arrays and lists can be iterated using for loops.
    • Code Example (Array):
      val array: Array[Int] = Array(1, 2, 3, 4, 5)
      for (element <- array) {
        println(s"Element: $element")
      }
      
    • Code Example (List):
      val list: List[String] = List("A", "B", "C")
      for (item <- list) {
        println(s"Item: $item")
      }
      
  12. Common patterns for using for loops in Scala:

    • Description: Common patterns include filtering, transforming, and iterating over collections using for loops.
    • Code Example (Filtering):
      val evens: Seq[Int] = for (i <- 1 to 10 if i % 2 == 0) yield i
      
    • Code Example (Transforming):
      val squares: Seq[Int] = for (i <- 1 to 5) yield i * i
      
    • Code Example (Iterating):
      val colors: Seq[String] = Seq("Red", "Green", "Blue")
      for (color <- colors) {
        println(s"Color: $color")
      }