WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Scala · Intermediate · question 22 of 100

What is the difference between a ’for’ loop and a ’for-comprehension’ in Scala?

📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

In Scala, a ‘for‘ loop and a ‘for‘ comprehension are similar constructs used for iterating over collections, but they are used in different scenarios and have some subtle differences.

1. ‘for‘ loop:

A ‘for‘ loop in Scala is used when you want to perform side-effects or repetitive actions, like modifying variables, printing output, or computing results. In this case, the primary purpose of the loop is to perform actions rather than directly generate a result.

Example:

// Print numbers 1 to 5
for (i <- 1 to 5) {
  println(s"Number: $i")
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

2. ‘for‘ comprehension (also known as ‘for‘ expression): A ‘for‘ comprehension is used when you want to transform a collection, iterate over multiple collections, or create new collections using the existing data. It is a more functional programming approach, as it returns a new collection without mutating or changing the original collection.

A ‘for‘ comprehension usually has a ‘yield‘ statement at the end, which generates the resulting collection.

Example:

val numbers = List(1, 2, 3, 4, 5)

val squares = for (number <- numbers) yield {
  number * number // square the number
}

println(s"Original numbers: $numbers")
println(s"Squared numbers: $squares")

Output:

Original numbers: List(1, 2, 3, 4, 5)
Squared numbers: List(1, 4, 9, 16, 25)

In summary, the main differences between a ‘for‘ loop and a ‘for‘ comprehension in Scala are:

- The ‘for‘ loop is intended for performing side-effects or repetitive actions, while the ‘for‘ comprehension is used for creating new collections or performing transformations.

- The ‘for‘ comprehension includes a ‘yield‘ statement, which generates the resulting collection.

- The ‘for‘ loop doesn’t return anything, whereas the ‘for‘ comprehension returns a new collection without mutating the original one.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Scala interview — then scores it.
📞 Practice Scala — free 15 min
📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

All 100 Scala questions · All topics