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 25 of 100

Explain the use of yield in for- comprehensions and its purpose.?

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

In Scala, the ‘yield‘ keyword is used in conjunction with for-comprehensions to return a new collection by applying some transformation on each element of the original collection. The purpose of ‘yield‘ is to allow a concise and readable syntax for performing this transformation.

A for-comprehension with ‘yield‘ has the following general form:

for (pattern <- c1;
     pattern2 <- c2; ...
     if condition) yield expression

Here, ‘c1‘, ‘c2‘ are collections, and ‘expression‘ represents the transformation on those collections’ elements.

Each iteration through the collections, the ‘expression‘ is evaluated and added to the resulting new collection. The type of the new collection will be the same as the original collection, following Scala’s best effort to preserve the type.

Here is an example:

val numbers = List(1, 2, 3, 4, 5)
val squaredNumbers = for (n <- numbers) yield n * n

In this example, ‘numbers‘ is a ‘List[Int]‘, and the for-comprehension iterates through each element ‘n‘ in ‘numbers‘, then evaluates the expression ‘n * n‘ (which squares each element), and stores the result in a new collection ‘squaredNumbers‘. The type of ‘squaredNumbers‘ will also be ‘List[Int]‘, and its value will be ‘List(1, 4, 9, 16, 25)‘.

The use of ‘yield‘ in this case allows for a more readable and concise syntax compared to using a combination of ‘map‘, ‘flatMap‘, and ‘filter‘ methods.

You can also use ‘yield‘ with additional generators and conditions, like this:

val matrix = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
val evenNumbers = for {
  row <- matrix
  number <- row
  if number % 2 == 0
} yield number

In this example, the ‘evenNumbers‘ variable will have the value ‘List(2, 4, 6, 8)‘ after the for-comprehension. Here, we have two generators (‘row <- matrix‘, ‘number <- row‘) and a condition to filter out odd numbers (‘if number

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