user3858193
user3858193

Reputation: 1518

How to add multiple if clause in Scala For Loop

Please let me know how can I add two if clause in a for loop with or option. for (name <- names **(if name.startsWith("S") || if name.endsWith("B".toLowerCase()) ) ) println(name)**

object ScalaList {
    def main(args: Array[String]): Unit = {
      val x = List(1,2,3,4,5)
      val x1 =List.range(10, 20)
      val x2 = 1::2::33::44::Nil
      val x3 = 100 :: x //(Prepending 100 in List x)
      val x4 = x1 ::: x2  //(Merging two list)
      val x5 = List.concat(x1 ,x2) //(Merging two list)

      x5.foreach {println} //Iterating list
      var sum=0
      var k = x.foreach (sum += _)

      val names =List("Sanjeeb","Hari","Adu","Bob")
      for (name <- names) println(name)
      for (name <- names if name.startsWith("S")                // <-- here is my if
          if name.endsWith("B".toLowerCase())  ) println(name)  // <-------


    }

}

Upvotes: 2

Views: 877

Answers (2)

dhg
dhg

Reputation: 52701

Use braces:

for {
  name <- names 
  if name.startsWith("S")
  if name.endsWith("B".toLowerCase())
} {
  println(name)
}

It makes for nice notation when you have multiple things you're iterating over or multiple ifs or those things mixed together.

A semicolon between the ifs would also work:

for (name <- names if name.startsWith("S"); if name.endsWith("B".toLowerCase())) println(name)

Upvotes: 3

MariuszS
MariuszS

Reputation: 31595

You really needs two ifs ?

if (name.startsWith("S") || name.endsWith("B".toLowerCase())

Upvotes: 1

Related Questions