Wednesday 19 August 2020

Scala: for loop

 ‘for’ loop is used to iterate over elements.

Syntax 1

for(loopVariable <- start to end){

    ......

    ......

}

 

Example : Below snippet print integers from 0 to 10.

for(i <- 0 to 10){

    println("Value of i is " + i)

}

scala> for(i <- 0 to 10){
     |    println("Value of i is " + i)
     | }
Value of i is 0
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Value of i is 5
Value of i is 6
Value of i is 7
Value of i is 8
Value of i is 9
Value of i is 10

As you see the output, for loop with ‘to’ keyword print values from starting number to ending number (inclusive).

 

Syntax 2: Using until

for(loopVariable <- start until end){

    ......

    ......

}

 

Example

for(i <- 0 until 10){

    println("Value of i is " + i)

}

scala> for(i <- 0 until 10){
     |    println("Value of i is " + i)
     | }
Value of i is 0
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Value of i is 5
Value of i is 6
Value of i is 7
Value of i is 8
Value of i is 9

As you see the output, for loop with ‘to’ keyword print values from starting number to ending number (exclusive).

 

‘for’ with ‘until’ keyword is useful while iterating over collection of elements.

scala> val hobbies = List("Football", "Cricket", "Blogging", "Trekking")
val hobbies: List[String] = List(Football, Cricket, Blogging, Trekking)

scala> for(hobbyIndex <- 0 until hobbies.size){
     |    println(hobbies(hobbyIndex))
     | }
Football
Cricket
Blogging
Trekking

You can achieve the same behavior using for-to, but you should traverse till hobbies.size-1.

scala> for(hobbyIndex <- 0 to hobbies.size-1){
     |    println(hobbies(hobbyIndex))
     | }
Football
Cricket
Blogging
Trekking

If you traverse till hobbies.size using for-to, you will end up in java.lang.IndexOutOfBoundsException.

scala> for(hobbyIndex <- 0 to hobbies.size){
     |    println(hobbies(hobbyIndex))
     | }
Football
Cricket
Blogging
Trekking
java.lang.IndexOutOfBoundsException: 4
  at scala.collection.LinearSeqOps.apply(LinearSeq.scala:116)
  at scala.collection.LinearSeqOps.apply$(LinearSeq.scala:113)
  at scala.collection.immutable.List.apply(List.scala:79)
  at $anonfun$res8$1(<console>:2)
  at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:190)
  ... 32 elided

Note

Scala does not have java for kind of loop.

for(initialization; condition; updation){

 

}



Previous                                                    Next                                                    Home

No comments:

Post a Comment