Scala – Loop Statements

  • Post category:Scala
  • Reading time:5 mins read

Scala Loop

This chapter takes you through the loop control structures in Scala programming languages. Scala for loop can be used to iterate over the elements in a collection. For example, given a sequence of integers:

Loop over a Sequence : Seq[Int]

scala> val numbers = Seq(1,2,3)
numbers: Seq[Int] = List(1, 2, 3)
scala> for (n <- numbers) println(n)
1
2
3

Loop over a List : List[Int]

val months = List(
    "Jan", 
    "Feb", 
    "March", 
    "April", 
    "May"
)

We can run a for loop just like we did in previous example:

for (x <- months ) println(x)

The foreach method with List

Below example shows how we can use foreach to print the previous list of strings:

months.foreach(println)

NOTE: foreach is available on most collections classes, including sequences, maps, and sets.

Using for and foreach with Map

Map is a collection of mappings that is key-value pair. We can also use for and foreach with a Scala Map (which is similar to a Java HashMap).

val details = Map(
    "Name"  -> "Proedu.co", 
    "Age"  -> 10, 
    "Address" -> "India"
)
// Example using For
for ((key,value) <- details) println(s"Key: $key, Value: $value")
// Example using foreach
details.foreach {
    case(key, value) => println(s"key: $key, value: $value")
}

Output

Key: Name, Value: Proedu.co
Key: Age, Value: 10
Key: Address, Value: India

For Expressions - Using yield keyword

While a for-loop is used for side effects (such as printing output), a for-expression is used to create new collections from existing collections.

Example - double every element in List using yield

scala> val nums = List(1,2,3)
scala> val doubledNums = for (n <- nums) yield n * 2
doubledNums: List[Int] = List(2, 4, 6)

Explanation : For every number n in the list of numbers nums, double each value, and then assign all of the new values to the variable doubledNums.

Example - Convert every element in List to lower case

scala> val names = List("PROEDU", "SCALA", "PROGRAMMING")
scala> val lowerNames = for (name <- names) yield name.toLowerCase()
lowerNames: List[String] = List(proedu, scala, programming)

Using yield andfor, We can yield a new collection from the existing collection that we are iterating over in the for-expression.

Using a block of code after yield keyword

Example - Convert first character of every element to Uppercase.

object TestDemo {
   def main(args: Array[String]): Unit = {
      val names = List("PROEDU", "SCALA", "PROGRAMMING")
      val lowerNames = for (name <- names) yield {
         val lowerCaseName = name.toLowerCase()
         val capName = lowerCaseName.capitalize
         capName
      }
      println(lowerNames)
   }
}

We can write the above program in just one expression as below

val capNames = for (name <- names) yield { name.toLowerCase().capitalize }
println(capNames)