📜  Scala for Loop(1)

📅  最后修改于: 2023-12-03 15:19:56.664000             🧑  作者: Mango

Scala for Loop

In Scala, the for loop is a fundamental construct used for iterating over a collection of elements or any sequence that can be converted to a collection. The for loop provides a concise and expressive way to iterate, filter, and transform data.

Syntax

The basic syntax of a for loop in Scala is as follows:

for (variable <- collection) {
    // loop body
}

Here, variable represents a placeholder that takes on the value of each element in the collection on each iteration.

Iterating Over a Range

One common use of the for loop is to iterate over a range of numbers. Scala provides a shorthand syntax for generating a sequence of numbers using the to keyword:

for (i <- 1 to 5) {
    println(i)
}

In this example, the for loop iterates over a range from 1 to 5 (inclusive) and prints each number.

Iterating Over Collections

Scala supports iterating over various collections, including lists, arrays, sets, and maps. You can use the for loop to process each element in the collection:

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

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

In this case, the for loop iterates over each element in the fruits list and prints it.

Filtering with Guards

Scala allows you to filter elements using guards within the for loop. A guard is a boolean expression that filters the elements based on a given condition:

for (i <- 1 to 10 if i % 2 == 0) {
    println(i)
}

This example prints only the even numbers from 1 to 10 by using the guard if i % 2 == 0.

Yielding Results

Scala for loops can also yield results by using the yield keyword. This allows you to create a new collection from the elements processed within the loop:

val evenNumbers = for (i <- 1 to 10 if i % 2 == 0) yield i

In this example, the evenNumbers collection will contain only the even numbers from 1 to 10.

Nested Loops

Scala supports nesting multiple for loops to iterate over multiple collections simultaneously:

val numbers = List(1, 2, 3)
val letters = List("A", "B", "C")

for (number <- numbers; letter <- letters) {
    println(number, letter)
}

This example shows how to iterate over both the numbers and letters collections simultaneously.

Conclusion

Scala's for loop is a powerful construct for iterating over collections and performing various operations on the elements. This flexibility, combined with the ability to filter and transform data, makes it a valuable tool for programmers.