Scala for/yield Example


In for loop example, we have seen how to iterate through the values. Suppose for each iterated element, we want to do some processing and return some information, in such case, we need to use a combination of for/yield.

We need to prefix the body of the for expression by the keyword yield, process the element in the block that follows yield and return the value.
When the for loop ends, the result will be in the form of a collection containing the yielded values.

Syntax of for yield:

for clauses yield body

For/Yield Example

Let’s see an example.

In the below example, we iterate through some skills, filter the programming languages and print the remaining skills.
As we iterate, we filter the skill if it is a programming language. The yield block contains the object to be returned.


object ForYieldExample {
  val skills = Array("Java", "Ruby", "Scala", "Spring", "JUnit", "TestNG", "Tomcat");
  val nonLanguageSkills = for (



More stuff in For/Yield Block

In our above example, we simply used yield to return the iterated element. In this example, we want to do something more in the yield block.

Let’s improve the above example, add more ‘Spring’ specific skills like ‘Spring Data’, ‘Spring Core’ etc.
If the skill is ‘Spring’ specific we want to simply return ‘Spring’ else the skill itself. To do this, we have added a simple if statement in the yield block.

if (skill contains "Spring") "spring" else skill


object ForYieldBlockExample {
  val skills = Array("Java", "Ruby", "Scala", "Spring Data", "Spring Core", "Spring Integration", "JUnit", "TestNG", "Tomcat");
  val nonLanguageSkills = for (
    skill <- skills 
    if skill != "Java" 
    if skill != "Ruby"
    if skill != "Scala"
  ) yield { if (skill contains "Spring") "spring" else skill }

  def main(args: Array[String]): Unit = {



Download the source code

This was an example about for/yield combination. You can download the source code here:


Comments are closed.