Monday 24 August 2020

Scala: for loop with if condition

Syntax 1

for(loopVariable <- start to end if condition){
    
}

Example 1: Print all the even numbers from 1 to 10 (inclusive)

scala> for(i <- 1 to 10 if i % 2 == 0){
     |   println(i)
     | }
2
4
6
8
10

Syntax 2

for(loopVariable <- start to end until condition){

   

}

 

Example 2: Print all the even numbers from 1 to 10 (exclusive)

scala> for(i <- 1 until 10 if i % 2 == 0){
     |   println(i)
     | }
2
4
6
8

Syntax 3

for(loopVariable <- list if condition) {

   

}

 

Example 3:

Print all the elements of the list that satisfies the given condition.

 

for(d <- data if d == "Krishna" || d == "Ram"){

    println("Welcome Mr. " + d)

}

scala> val data = List("Hello", "Krishna", "Hi", "How", "Ram")
val data: List[String] = List(Hello, Krishna, Hi, How, Ram)

scala> for(d <- data if d == "Krishna" || d == "Ram"){
     |    println("Welcome Mr. " + d)
     | }
Welcome Mr. Krishna
Welcome Mr. Ram




Previous                                                    Next                                                    Home

No comments:

Post a Comment